diff --git a/.github/CODEOWNERS b/.github/CODEOWNERS index 5a1caa5880438..34f244833da37 100644 --- a/.github/CODEOWNERS +++ b/.github/CODEOWNERS @@ -6,33 +6,34 @@ ########### # Catch all -/sdk/ @joshfree @jonathangiles +/sdk/ @joshfree @jonathangiles # Service teams -/sdk/appconfiguration/ @mssfang @alzimmermsft @conniey @sima-zhu -/sdk/batch/ @xingwu1 @bgklein @matthchr -/sdk/core/ @alzimmermsft @jianghaolu @srnagar @hemanttanwar -/sdk/cosmos/ @moderakh @christopheranderson @kushagraThapar -/sdk/eventhubs/ @conniey @srnagar @mssfang -/sdk/identity/ @jianghaolu @g2vinay @hemanttanwar -/sdk/keyvault/ @g2vinay @samvaity -/sdk/servicebus/ @yvgopal @nemakam -/sdk/tracing/ @samvaity @alzimmermsft +/sdk/appconfiguration/ @mssfang @alzimmermsft @conniey @sima-zhu +/sdk/batch/ @xingwu1 @bgklein @matthchr +/sdk/core/ @alzimmermsft @jianghaolu @srnagar @hemanttanwar +/sdk/cosmos/ @moderakh @christopheranderson @kushagraThapar +/sdk/eventhubs/ @conniey @srnagar @mssfang +/sdk/identity/ @jianghaolu @g2vinay @hemanttanwar +/sdk/keyvault/ @g2vinay @samvaity +/sdk/servicebus/ @yvgopal @nemakam +/sdk/textanalytics/ @samvaity @mssfang +/sdk/tracing/ @samvaity @alzimmermsft -/sdk/storage/ @rickle-msft @jaschrep-msft @gapra-msft @alzimmermsft @sima-zhu +/sdk/storage/ @rickle-msft @jaschrep-msft @gapra-msft @alzimmermsft @sima-zhu # Management Plane -/**/resource-manager/ @yaohaizh -/sdk/**/azure-mgmt-*/ @yaohaizh +/**/resource-manager/ @yaohaizh +/sdk/**/azure-mgmt-*/ @yaohaizh ########### # Eng Sys ########### -/eng/ @JimSuplizio @mitchdenny @weshaggard @danieljurek -/eng/code-quality-reports/ @mssfang @JonathanGiles -/eng/jacoco-test-coverage/ @srnagar @JonathanGiles -/eng/spotbugs-aggregate-report/ @srnagar @JonathanGiles -/parent/ @JimSuplizio +/eng/ @JimSuplizio @mitchdenny @weshaggard @danieljurek +/eng/code-quality-reports/ @mssfang @JonathanGiles +/eng/jacoco-test-coverage/ @srnagar @JonathanGiles +/eng/spotbugs-aggregate-report/ @srnagar @JonathanGiles +/parent/ @JimSuplizio -/**/tests.yml @danieljurek -/**/ci.yml @mitchdenny +/**/tests.yml @danieljurek +/**/ci.yml @mitchdenny diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 3e515e4862e44..152f0fc25560c 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -87,24 +87,23 @@ The dependency-version should be set to the most recent released version and the `com.azure:azure-identity;1.0.0-preview.4;1.0.0-preview.5` -Note: In the case of a new or unreleased artifact both versions will be the same. +Note: In the case of a new artifact both versions will be the same. In the case of a released artifact, the dependecny version should be the latest released version. ### Libraries vs External Dependencies Libraries refer to things that are built and released as part of the Azure SDK. Libraries have a current version and a dependency version. -External Dependencies refer to dependencies for things that are not built and released as part of the Azure SDK regardless of the source. External Dependencies will only ever have one version. +External Dependencies refer to dependencies for things that are not built and released as part of the Azure SDK regardless of the source. External Dependencies will only ever have a dependency version. -### Current version vs Dependency version +### Current version, Dependency version and Unreleased Dependency version Current version - This is the version we should be using when defining a component in its POM file and also when dependent components are built within the same pipeline. The current version is the version currently in development. -Dependency version - This is the version we should be using when a given library is a dependency outside of a particular area. This should be the latest released version of the package. +Dependency version - This is the version we should be using when a given library is a dependency outside of a particular area. This should be the latest released version of the package whenever possible. +Unreleased Dependency version – Whenever possible, libraries should be using the latest released version for dependencies but there is the case where active development in one library is going to be needed by another library or libraries that are built in separate pipelines. These types of changes are specifically additive and not breaking. Once a library has GA’d, nothing short of breaking changes should ever force the dependency versions across the repo to an unreleased version. The reason for this is that it would prevent other libraries, that don’t need this change, from releasing. -For example: `com.azure:azure-storage-blob-batch` has dependencies on `com.azure:azure-core`, `com.azure:azure-core-http-netty` and `com.azure:azure-storage-blob`. Because `com.azure:azure-core` and `com.azure:azure-core-http-netty` are both built outside of azure-storage pipeline we should be using the released or *Dependency* versions of these when they're dependencies of another library. Similarly, libraries built as part of the same pipeline, that have interdependencies, should be using the Current version. Since `com.azure:azure-storage-blob-batch` and `com.azure:azure-storage-blob` are both built part of the azure-batch pipeline when `com.azure:azure-storage-blob` is declared as a dependency of `com.azure:azure-storage-blob-batch` it should be the *Current* version. +An example of Current vs Dependency versions: `com.azure:azure-storage-blob-batch` has dependencies on `com.azure:azure-core`, `com.azure:azure-core-http-netty` and `com.azure:azure-storage-blob`. Because `com.azure:azure-core` and `com.azure:azure-core-http-netty` are both built outside of azure-storage pipeline we should be using the released or *Dependency* versions of these when they're dependencies of another library. Similarly, libraries built as part of the same pipeline, that have interdependencies, should be using the Current version. Since `com.azure:azure-storage-blob-batch` and `com.azure:azure-storage-blob` are both built part of the azure-batch pipeline when `com.azure:azure-storage-blob` is declared as a dependency of `com.azure:azure-storage-blob-batch` it should be the *Current* version. -This is going to be especially important after GA when releases aren't going to be the entire Azure SDK every time. If we're releasing a patch for a targeted azure-storage fix then we shouldn't need to build and release azure-core, we should be targeting the released versions and only building/releasing that update to azure-storage. It's worth noting that right now, in the version_client.txt, the dependency/current versions are the same. This will change once we GA, at which point the current version should be ahead of the dependency version. - -What about README files? Right now the README files in the repo end up getting into an odd state since things like samples and versions can get updated during the development process. We're in the process of versioning documentation with the releases which means that the docs are snapshot at the time of the release and then versioned and stored. This will allow the README files in the repo to have updated samples and versions that are setup for the next release. +An example of an Unreleased Dependency version: Additive, not breaking, API changes have been made to `com.azure:azure-core`. `com.azure:azure-storage-blob` has a dependency on `com.azure:azure-core` and requires the additive API change that has not yet been released. An unreleased entry needs to be created in [version_client.txt](./eng/versioning/version_client.txt), under the unreleased section, with the following format: `unreleased_:;dependency-version`, in this example that would be `unreleased_com.azure:azure-core;1.2.0` (this should match the 'current' version of core). The dependency update tags in the pom files that required this dependency would now reference `{x-version-update;unreleased_com.azure:azure-core;dependency}`. Once the updated library has been released the unreleased dependency version should be removed and the POM file update tags should be referencing the released version. ### Tooling, version files and marker tags @@ -112,6 +111,7 @@ All of the tooling lives under the **eng\versioning** directory. - version_client.txt - Contains the Client library and versions - version_data.txt - Contains Data library and versions +- external_dependencies.txt - Contains the external dependency versions - update_versions.py - This is just a basic python script that will climb through the source tree and update POM and README files. The script utilizes tags within the files to do replacements and the tags are slightly different between the POM and README files. - set_versions.py - This script should only be used by the build system when we start producing nightly ops builds. @@ -135,56 +135,31 @@ In README files this ends up being slightly different. Because the version tag i ``` [//]: # ({x-version-update-end}) -What if I've got something that, for whatever reason, shoudln't be updated? There's a tag for that. - -`` - -In theory, absence of an x-version-update tag would do the same thing but the tooling is still being developed and eventually there will be checkin blockers if xml has a version element with no tag. - ### What does the process look like? Let's say we've GA'd and I need to tick up the version of azure-storage libraries how would I do it? Guidelines for incrementing versions after release can be found [here](https://github.com/Azure/azure-sdk/blob/master/docs/policies/releases.md#incrementing-after-release). -1. I'd open up eng\versioning\version_client.txt and update the current-versions of the libraries that are built and released as part of the azure storage pipeline. This list can be found in pom.service.xml under the sdk/storage directory. It's worth noting that any module entry starting with "../" are external module dependencies and not something that's released as part of the pipeline. Once we GA, these build dependencies for library components outside of a given area should go away and be replaced with downloading the appropriate dependency from Maven like we do for external dependencies. +1. I'd open up eng\versioning\version_client.txt and update the current-versions of the libraries that are built and released as part of the azure storage pipeline. This list can be found in pom.service.xml under the sdk/storage directory. It's worth noting that any module entry starting with "../" are external module dependencies and not something that's released as part of the pipeline. Dependencies for library components outside of a given area would be downloading the appropriate dependency from Maven like we do for external dependencies. 2. Execute the update_versions python script from the root of the enlistment `python eng/versioning/update_versions.py --ut libary --bt client` This will go through the entire source tree and update all of the references in the POM and README files with the updated versions. Git status will show all of the modified files. 3. Review and submit a PR with the modified files. -### Next steps: External dependencies, Management plane and service pipeline changes +### Next steps: Management plane -- External dependencies. Right now there are only version files for client and data (eng\versioning\version_\[client|data\].txt) which only encompass the built binaries for their respective tracks. External dependencies for both client and data are next on the list which should allow modification of the parent/pom.xml to remove the list of version properties and dependency management sections which brings things one step closer to not having to publish the parent pom. - Management plane. Management is in the process of being moved to service pipeline builds. The versioning work needs to wait until that work is finished. -- Service pipeline changes. The service pipelines currently have to build not only the libraries that are part of that pipeline but also the Azure SDK libraries that are dependencies. Once we GA and can start targeting the released version of those packages and pulling them from Maven instead of building them. An good example of this would be in sdk/appconfiguration/pom.service.xml where to build azure-data-appconfiguration we end up building azure-core, azure-core-test and azure-core-http-netty along with azure-data-appconfiguration instead of just building azure-data-appconfiguration. - -### How are versioning and dependencies going to impact development after GA? - -As mentioned above, in the service pipeline changes, the plan after we GA is to start targeting the released version of the packages and pulling them from Maven. This is going to fundamentally change some aspects of the development process especially when work needs to be done on given library that requires dependency changes in one or more libraries. - -- **Scenario 1: Making changes to a single library which is not a dependency of any other libraries:** This ends up being the most straightforward scenario and really isn't much different than it is today. - - [ ] Appropriately increase the version - - [ ] Make the code changes - - [ ] Submit the PR - - [ ] Merge the PR - - [ ] Publish the new version - -- **Scenario 2: Making changes to a library that also requires dependency changes:** Right now things are in a state where dependency changes can be made along with libraries that depend on them because of the project dependencies in the service pom files. Local development isn't going to change that much except when changing the version of a library and its dependency or dependencies means that the service poms are going to have to be built, and installed, in the appropriate order. This is because these new versions of the library dependencies won't yet be released and Maven will need to find these in the local cache. The biggest change to the process is going to be around PRs and publishing. Separate PRs are going to have to be submitted in order, with dependencies being submitted first. This is necessary because the dependencies need to be published in order to allow things that depend on them to continue using the published version. Trying to submit everything in one PR would cause build breaks since the dependency being referenced is a version not yet published. An example of this would be making changes to `com.azure:azure-storage-common` that also required dependency changes to `com.azure:azure-identity`. - Changes are going to have to be made to `com.azure:azure-identity` first. - - [ ] Appropriately increase the version of `com.azure:azure-identity` - - [ ] Make the code changes - - [ ] Build and optionally install locally - This isn't completely necessary other than to install the updated version of the dependency into the local cache on the machine. The alternative to this would be to publish (DevOps or otherwise) and reference that version of the dependency after the release. Either one would allow `com.azure:azure-storage-common` to use the updated version of `com.azure:azure-identity` - - [ ] Submit the PR for the `com.azure:azure-identity` - - [ ] Merge the PR for the `com.azure:azure-identity` - - [ ] Publish the `com.azure:azure-identity` with the updated version. - - Only after the dependency `com.azure:azure-identity` has been published can the PR for `com.azure:azure-storage-common` be created. - - [ ] Appropriately increase the version of `com.azure:azure-storage-common` and the dependency version of `com.azure:azure-identity` in its pom file. - - [ ] Make the code changes, if any - - [ ] Build/Test or whatever - - [ ] Submit the PR for `com.azure:azure-storage-common` - - [ ] Merge the PR for `com.azure:azure-storage-common` - - [ ] Publish the PR for `com.azure:azure-storage-common` + +### Making changes to an already GA'd library that require other libraries to depend on the unreleased version + +This is where the `unreleased_` dependency tags come into play. Using the Unreleased Dependency example above, where `com.azure:azure-storage-blob` has a dependency on an unreleased `com.azure:azure-core`: + +- [ ] Make the additive changes to `com.azure:azure-core` +- [ ] In [version_client.txt](./eng/versioning/version_client.txt) add the entry for the unreleased azure core in the unreleased section at the bottom of the file. The entry would look like `unreleased_com.azure:azure-core;`. + Note: The version of the library referenced in the unreleased version tag should match the current version of that library. +- [ ] In the pom.xml file for `com.azure:azure-storage-blob`, the dependency tag for `com.azure:azure-core` which was originally `{x-version-update;com.azure:azure-core-test;dependency}` would now become `{x-version-update;unreleased_com.azure:azure-core-test;dependency}` +After the unreleased version of `com.azure:azure-core` was released but before `com.azure:azure-storage-blob` has been released. +- [ ] In [version_client.txt](./eng/versioning/version_client.txt) the the dependency version of `com.azure:azure-core` would become the released version and the "unreleased_" entry, at this time, would be removed. +- [ ] In the pom.xml file for `com.azure:azure-storage-blob`, the dependency tag for `com.azure:azure-core` would get changed back to `{x-version-update;com.azure:azure-core-test;dependency}` ### Nightly package builds diff --git a/README.md b/README.md index 93b092f3bdfe8..da2407441a892 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ This repository is intended for active development of the Azure SDK for Java. Fo ### Important -The Azure SDK team is pleased to make available the November 2019 client library General Availability (GA) release. We strongly recommend using the GA libraries in all production environments as these libraries are well tested and officially supported by Microsoft. More details, including installation instructions can be found here [here](https://azure.github.io/azure-sdk/releases/2019-11/java.html). +The Azure SDK team is pleased to make available the January 2020 client library General Availability (GA) release. We strongly recommend using the GA libraries in all production environments as these libraries are well tested and officially supported by Microsoft. More details, including installation instructions can be found here [here](https://azure.github.io/azure-sdk/releases/2019-11/java.html). ## Getting started @@ -16,45 +16,39 @@ For tutorials, samples, quick starts and other documentation, visit [Azure for J ### Prerequisites -Java 8 or later is required to use the November 2019 client libraries, otherwise Java 7 or later is required. +Java 8 or later is required to use the January 2020 client libraries, otherwise Java 7 or later is required. ## Latest Release Each service might have a number of libraries available from each of the following categories: -- [Client: GA Decemeber 2019 Releases](#Client-GA-Decemeber-2019-Releases) +- [Client: GA January 2020 Releases](#Client-GA-January-2020-Releases) - [Client - Previous Versions](#Client-Previous-Versions) - [Management](#Management) -### Client: GA December 2019 Releases +### Client: GA January 2020 Releases -New wave of packages that were released in December 2019 client library as General Availability (GA) and several others that were released in **beta**. These libraries follow the [Azure SDK Design Guidelines for Java](https://azure.github.io/azure-sdk/java/guidelines/) and share a number of core features such as HTTP retries, logging, transport protocols, authentication protocols, etc., so that once you learn how to use these features in one client library, you will know how to use them in other client libraries. You can learn about these shared features [here](https://github.com/Azure/azure-sdk-for-java/blob/azure-core_1.1.0/sdk/core/azure-core/README.md). +New wave of packages that were released in January 2020 client library as General Availability (GA) and several others that were released in **beta**. These libraries follow the [Azure SDK Design Guidelines for Java](https://azure.github.io/azure-sdk/java/guidelines/) and share a number of core features such as HTTP retries, logging, transport protocols, authentication protocols, etc., so that once you learn how to use these features in one client library, you will know how to use them in other client libraries. You can learn about these shared features [here](https://github.com/Azure/azure-sdk-for-java/blob/azure-core_1.2.0/sdk/core/azure-core/README.md). These libraries can be easily identified by sdk/ folder, package, and namespaces names starting with `azure-`, e.g. `azure-keyvault`. -The libraries released in the GA December 2019 release: -- [Identity](https://github.com/Azure/azure-sdk-for-java/blob/azure-identity_1.0.1/sdk/identity/azure-identity/README.md) -- [Key Vault Keys](https://github.com/Azure/azure-sdk-for-java/blob/azure-security-keyvault-keys_4.0.1/sdk/keyvault/azure-security-keyvault-keys/README.md) -- [Key Vault Secrets](https://github.com/Azure/azure-sdk-for-java/blob/azure-security-keyvault-secrets_4.0.1/sdk/keyvault/azure-security-keyvault-secrets/README.md) -- [Storage Blobs](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-blob_12.1.0/sdk/storage/azure-storage-blob/README.md) -- [Storage Blobs Batch](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-blob-batch_12.1.0/sdk/storage/azure-storage-blob-batch/README.md) -- [Storage Blobs Cryptography](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-blob-cryptography_12.1.0/sdk/storage/azure-storage-blob-cryptography/README.md) -- [Storage Queues](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-queue_12.1.0/sdk/storage/azure-storage-queue/README.md) -- [Storage File Share](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-file-share_12.0.0/sdk/storage/azure-storage-file-share/README.md) - -The libraries released in the December 2019 beta: -- [App Configuration](https://github.com/Azure/azure-sdk-for-java/tree/azure-data-appconfiguration_1.0.0-beta.7/sdk/appconfiguration/azure-data-appconfiguration/README.md) -- [Event Hubs](https://github.com/Azure/azure-sdk-for-java/blob/azure-messaging-eventhubs_5.0.0-beta.6/sdk/eventhubs/azure-messaging-eventhubs/README.md) -- [Event Hubs Checkpoint Store](https://github.com/Azure/azure-sdk-for-java/blob/azure-messaging-eventhubs-checkpointstore-blob_1.0.0-beta.4/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md) -- [Key Vault Certificates](https://github.com/Azure/azure-sdk-for-java/blob/azure-security-keyvault-certificates_4.0.0-beta.6/sdk/keyvault/azure-security-keyvault-certificates/README.md) -- [OpenCensus Tracing](https://github.com/Azure/azure-sdk-for-java/blob/azure-core-tracing-opencensus_1.0.0-beta.5/sdk/core/azure-core-tracing-opencensus/README.md) -- [OpenTelemetry Tracing](https://github.com/Azure/azure-sdk-for-java/blob/azure-core-tracing-opentelemetry_1.0.0-beta.1/sdk/core/azure-core-tracing-opentelemetry/README.md) +The libraries released in the GA January 2020 release is listed below. +- [January 2020](https://azure.github.io/azure-sdk/releases/2020-01/java.html) + +#### Client: Earlier GA Releases + +- [December 2019](https://azure.github.io/azure-sdk/releases/2019-12/java.html) +- [November 2019](https://azure.github.io/azure-sdk/releases/2019-11/java.html) +- [October 2019](https://azure.github.io/azure-sdk/releases/2019-10-11/java.html) +- [September 2019](https://azure.github.io/azure-sdk/releases/2019-09-17/java.html) +- [August 2019](https://azure.github.io/azure-sdk/releases/2019-08-06/java.html) +- [July 2010](https://azure.github.io/azure-sdk/releases/2019-07-10/java.html) > NOTE: If you need to ensure your code is ready for production use one of the stable, non-preview libraries. ### Client: Previous Versions -Last stable versions of packages that have been provided for usage with Azure and are production-ready. These libraries provide similar functionalities to the preview libraries, as they allow you to use and consume existing resources and interact with them, for example: upload a blob. Stable library directories start with `microsoft-azure-`, e.g. `microsoft-azure-keyvault`. They might not implement the [guidelines](https://azure.github.io/azure-sdk/java_introduction.html) or have the same feature set as the Novemeber releases. They do however offer wider coverage of services. +Last stable versions of packages that have been provided for usage with Azure and are production-ready. These libraries provide similar functionalities to the preview libraries, as they allow you to use and consume existing resources and interact with them, for example: upload a blob. Stable library directories start with `microsoft-azure-`, e.g. `microsoft-azure-keyvault`. They might not implement the [guidelines](https://azure.github.io/azure-sdk/java_introduction.html) or have the same feature set as the GA releases. They do however offer wider coverage of services. ### Management @@ -71,7 +65,7 @@ Libraries which enable you to provision specific resources. They are responsible ## Navigating the repository ### Master branch -The master branch has the most recent code with new features and bug fixes. It does **not** represent latest released **GA** SDK. See [above](#Client-GA-November-2019-Releases) for latest **GA** release.
+The master branch has the most recent code with new features and bug fixes. It does **not** represent latest released **GA** SDK. See [above](#Client-GA-January-2020-Releases) for latest **GA** release.
### Release branches (Release tagging) diff --git a/eng/.docsettings.yml b/eng/.docsettings.yml index 5b049a71dcf4b..690ec90b26cfb 100644 --- a/eng/.docsettings.yml +++ b/eng/.docsettings.yml @@ -121,6 +121,7 @@ known_content_issues: - ['sdk/storage/azure-storage-queue/swagger/README.md', '#3113'] - ['sdk/storage/microsoft-azure-storage-blob/README.md', '#3113'] - ['sdk/storage/microsoft-azure-storage-blob/swagger/README.md', '#3113'] + - ['sdk/storage/azure-storage-blob-nio/README.md', '#3113'] - ['sdk/storage/README.md', '#3113'] - ['sdk/textanalytics/azure-ai-textanalytics/swagger/README.md', '#3113'] - ['sdk/template/azure-sdk-template/README.md','has other required sections'] diff --git a/eng/docgeneration/Generate-DocIndex.ps1 b/eng/docgeneration/Generate-DocIndex.ps1 new file mode 100644 index 0000000000000..a5a7466c58fc3 --- /dev/null +++ b/eng/docgeneration/Generate-DocIndex.ps1 @@ -0,0 +1,164 @@ +[CmdletBinding()] +Param ( + $RepoRoot, + $DocGenDir +) + +Write-Verbose "Name Reccuring paths with variable names" +$DocFxTool = "${RepoRoot}/docfx/docfx.exe" +$DocOutDir = "${RepoRoot}/docfx_project" + +Write-Verbose "Initializing Default DocFx Site..." +& "${DocFxTool}" init -q -o "${DocOutDir}" + +Write-Verbose "Copying template and configuration..." +New-Item -Path "${DocOutDir}" -Name "templates" -ItemType "directory" +Copy-Item "${DocGenDir}/templates/*" -Destination "${DocOutDir}/templates" -Force -Recurse +Copy-Item "${DocGenDir}/docfx.json" -Destination "${DocOutDir}/" -Force + +Write-Verbose "Creating Index using service directory and package names from repo..." +# The service mapper is used to map the directory names to the service names to produce +# a more friendly index. If something isn't in the mapper then the default will just be +# the service name in all caps +$serviceMapHash = Get-Content -Path "${DocGenDir}/service-mapper.json" | ConvertFrom-Json -AsHashtable + +# There are some artifact that show up, due to the way we do discovery, that are never shipped. +# Keep a list of those here and anything we don't want to ship can be added to here which will +# cause them to get skipped when generating the DocIndex +$ArtifactsToSkip = ( +'azure-cosmos-benchmark', +'azure-sdk-template' +) + +# The list of services is being constructed from the directory list under the sdk folder +# which, right now, only contains client/data directories. When management is moved to +# the under sdk it'll automatically get picked up. +$ServiceListData = Get-ChildItem "${RepoRoot}/sdk" -Directory +$YmlPath = "${DocOutDir}/api" +New-Item -Path $YmlPath -Name "toc.yml" -Force +foreach ($Dir in $ServiceListData) +{ + $mappedDir = "" + if ($serviceMapHash.ContainsKey($Dir.Name)) + { + $mappedDir = $serviceMapHash[$Dir.Name] + } + else + { + $mappedDir = $Dir.Name.ToUpper() + } + + # Store the list of artifacts into the arrays and write them into the .md file + # after processing the list of subdirectories. This will allow the correct + # division of the artifacts under the Client or Management headings + $clientArr = @() + $mgmtArr = @() + + $PkgList = Get-ChildItem $Dir.FullName -Directory -Exclude changelog, faq, .github, build + if (($PkgList | Measure-Object).count -eq 0) + { + continue + } + foreach ($Pkg in $PkgList) + { + # Load the pom file to pull the artifact name and grab the + # parent's relative path to see which parent pom is being + # used to determine whether or not the artifact is client + # or management. + $PomPath = Join-Path -Path $Pkg -ChildPath "pom.xml" + + # no pom file = nothing to process + if (Test-Path -path $PomPath) + { + $xml = New-Object xml + $xml.Load($PomPath) + + # Get the artifactId from the POM + $artifactId = $xml.project.artifactId + + $parent = $xml.project.parent.relativePath + + # If this is an artifact that isn't shipping then just + # move on to the next one + if ($ArtifactsToSkip -contains $artifactId) + { + Write-Output "skipping $artifactId" + continue + } + + # If the parent is null or empty then the pom isn't directly including + # one of the pom.[client|data|management].xml and needs to be specially + # handled + if (("" -eq $parent) -or ($null -eq $parent)) + { + # Cosmos has a root pom which includes pom.client.xml that won't + # be detected by this logic. It's easier to deal with specially + # than it is to try and climb the pom chain here. + if ($Dir.BaseName -eq 'cosmos') + { + $clientArr += $artifactId + } + else + { + Write-Host "*snowflake* Pom $PomPath, has a null or empty relative path." + } + } + else + { + if (($parent.IndexOf('pom.client.xml') -ne -1) -or ($parent.IndexOf('pom.data.xml') -ne -1)) + { + $clientArr += $artifactId + } + else + { + $mgmtArr += $artifactId + } + } + } + } + # Only create this if there's something to create + #if (($clientArr.Count -gt 0) -or ($mgmtArr.Count -gt 0)) + if ($clientArr.Count -gt 0) + { + New-Item -Path $YmlPath -Name "$($Dir.Name).md" -Force + Add-Content -Path "$($YmlPath)/toc.yml" -Value "- name: $($mappedDir)`r`n href: $($Dir.Name).md" + # loop through the arrays and add the appropriate artifacts under the appropriate headings + if ($clientArr.Count -gt 0) + { + Add-Content -Path "$($YmlPath)/$($Dir.Name).md" -Value "# Client Libraries" + foreach($lib in $clientArr) + { + Write-Host "Write $($lib) to $($Dir.Name).md" + Add-Content -Path "$($YmlPath)/$($Dir.Name).md" -Value "#### $lib" + } + } + # For the moment there are no management docs and with the way some of the libraries + # in management are versioned is a bit wonky. They aren't versioned by releasing a new + # version with the same groupId/artifactId, they're versioned with the same artifactId + # and version with a different groupId and the groupId happens to include the date. For + # example, the artifact/version of azure-mgmt-storage:1.0.0-beta has several different + # groupIds. com.microsoft.azure.storage.v2016_01_01, com.microsoft.azure.storage.v2017_10_01, + # com.microsoft.azure.storage.v2018_11_01 etc. + #if ($mgmtArr.Count -gt 0) + #{ + # Add-Content -Path "$($YmlPath)/$($Dir.Name).md" -Value "# Management Libraries" + # foreach($lib in $mgmtArr) + # { + # Write-Output "Write $($lib) to $($Dir.Name).md" + # Add-Content -Path "$($YmlPath)/$($Dir.Name).md" -Value "#### $lib" + # } + #} + } +} + +Write-Verbose "Creating Site Title and Navigation..." +New-Item -Path "${DocOutDir}" -Name "toc.yml" -Force +Add-Content -Path "${DocOutDir}/toc.yml" -Value "- name: Azure SDK for Java APIs`r`n href: api/`r`n homepage: api/index.md" + +Write-Verbose "Copying root markdowns" +Copy-Item "$($RepoRoot)/README.md" -Destination "${DocOutDir}/api/index.md" -Force + +Write-Verbose "Building site..." +& "${DocFxTool}" build "${DocOutDir}/docfx.json" + +Copy-Item "${DocGenDir}/assets/logo.svg" -Destination "${DocOutDir}/_site/" -Force \ No newline at end of file diff --git a/eng/jacoco-test-coverage/pom.xml b/eng/jacoco-test-coverage/pom.xml index 83d24ddebc8e5..15ca959641eeb 100644 --- a/eng/jacoco-test-coverage/pom.xml +++ b/eng/jacoco-test-coverage/pom.xml @@ -44,22 +44,22 @@ com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 com.azure azure-core-amqp - 1.0.0-beta.9 + 1.0.1 com.azure azure-core-http-netty - 1.2.0-beta.1 + 1.3.0-beta.1 com.azure azure-core-http-okhttp - 1.1.0-beta.1 + 1.2.0-beta.1 @@ -70,17 +70,17 @@ - + com.azure azure-core-tracing-opencensus - 1.0.0-beta.6 + 1.0.0-beta.7 com.azure azure-data-appconfiguration - 1.0.0-beta.8 + 1.0.1 com.azure @@ -90,52 +90,57 @@ com.azure azure-security-keyvault-certificates - 4.0.0-beta.8 + 4.0.0 com.azure azure-security-keyvault-keys - 4.1.0-beta.1 + 4.1.0 com.azure azure-security-keyvault-secrets - 4.1.0-beta.1 + 4.1.0 com.azure azure-messaging-eventhubs - 5.0.0-beta.7 + 5.0.1 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.0.0-beta.5 + 1.0.1 com.azure azure-storage-common - 12.2.0-beta.2 + 12.2.0 com.azure azure-storage-blob - 12.2.0-beta.2 + 12.2.0 com.azure azure-storage-blob-batch - 12.2.0-beta.1 + 12.2.0 com.azure azure-storage-blob-cryptography - 12.2.0-beta.1 + 12.2.0 + + + com.azure + azure-storage-blob-nio + 12.0.0-beta.1 com.azure azure-storage-file-share - 12.1.0-beta.2 + 12.1.0 com.azure @@ -145,7 +150,7 @@ com.azure azure-storage-queue - 12.2.0-beta.2 + 12.2.0 diff --git a/eng/pipelines/docindex.yml b/eng/pipelines/docindex.yml index 4d89a078dba24..142c331cb6764 100644 --- a/eng/pipelines/docindex.yml +++ b/eng/pipelines/docindex.yml @@ -28,182 +28,13 @@ jobs: - pwsh: | Invoke-WebRequest -Uri "https://github.com/dotnet/docfx/releases/download/v2.43.2/docfx.zip" ` -OutFile "docfx.zip" | Wait-Process; Expand-Archive -Path "docfx.zip" -DestinationPath "./docfx/" - workingDirectory: $(Build.BinariesDirectory) + workingDirectory: $(Build.SourcesDirectory) displayName: Download and Extract DocFX - - task: CmdLine@2 - displayName: Provision DocFX Directory - inputs: - script: $(Build.BinariesDirectory)/docfx/docfx.exe init -q - workingDirectory: $(Build.SourcesDirectory) - failOnStderr: true - - pwsh: New-Item -Path . -Name "templates" -ItemType "directory" - displayName: Create Template Directory - workingDirectory: $(Build.SourcesDirectory)/docfx_project/ - - task: CopyFiles@2 - displayName: Copy Template to templates folder - inputs: - sourceFolder: $(Build.SourcesDirectory)/eng/docgeneration/templates - content: '**\*' - targetFolder: $(Build.SourcesDirectory)/docfx_project/templates - overWrite: true - - pwsh: ls - workingDirectory: $(Build.SourcesDirectory)/docfx_project/ - - pwsh: ls - workingDirectory: $(Build.SourcesDirectory)/docfx_project/templates - - pwsh: | - Copy-Item "$(Build.SourcesDirectory)/eng/docgeneration/docfx.json" -Destination "$(Build.SourcesDirectory)/docfx_project/" -Force - displayName: Copy over docfx.json - - pwsh: | - - # The service mapper is used to map the directory names to the service names to produce - # a more friendly index. If something isn't in the mapper then the default will just be - # the service name in all caps - $serviceMapHash = Get-Content -Path "$(Build.SourcesDirectory)/eng/docgeneration/service-mapper.json" | ConvertFrom-Json -AsHashtable - - # There are some artifact that show up, due to the way we do discovery, that are never shipped. - # Keep a list of those here and anything we don't want to ship can be added to here which will - # cause them to get skipped when generating the DocIndex - $ArtifactsToSkip = ( - 'azure-cosmos-benchmark', - 'azure-sdk-template' - ) - - # The list of services is being constructed from the directory list under the sdk folder - # which, right now, only contains client/data directories. When management is moved to - # the under sdk it'll automatically get picked up. - $ServiceListData = Get-ChildItem "$(Build.SourcesDirectory)/sdk" -Directory - $YmlPath = "$(Build.SourcesDirectory)/docfx_project/api" - New-Item -Path $YmlPath -Name "toc.yml" -Force - foreach ($Dir in $ServiceListData) - { - $mappedDir = "" - if ($serviceMapHash.ContainsKey($Dir.Name)) - { - $mappedDir = $serviceMapHash[$Dir.Name] - } - else - { - $mappedDir = $Dir.Name.ToUpper() - } - # Store the list of artifacts into the arrays and write them into the .md file - # after processing the list of subdirectories. This will allow the correct - # division of the artifacts under the Client or Management headings - $clientArr = @() - $mgmtArr = @() - - $PkgList = Get-ChildItem $Dir.FullName -Directory -Exclude changelog, faq, .github, build - if (($PkgList | Measure-Object).count -eq 0) - { - continue - } - foreach ($Pkg in $PkgList) - { - # Load the pom file to pull the artifact name and grab the - # parent's relative path to see which parent pom is being - # used to determine whether or not the artifact is client - # or management. - $PomPath = Join-Path -Path $Pkg -ChildPath "pom.xml" - - # no pom file = nothing to process - if (Test-Path -path $PomPath) - { - $xml = New-Object xml - $xml.Load($PomPath) - - # Get the artifactId from the POM - $artifactId = $xml.project.artifactId - - $parent = $xml.project.parent.relativePath - - # If this is an artifact that isn't shipping then just - # move on to the next one - if ($ArtifactsToSkip -contains $artifactId) - { - Write-Output "skipping $artifactId" - continue - } - - # If the parent is null or empty then the pom isn't directly including - # one of the pom.[client|data|management].xml and needs to be specially - # handled - if (("" -eq $parent) -or ($null -eq $parent)) - { - # Cosmos has a root pom which includes pom.client.xml that won't - # be detected by this logic. It's easier to deal with specially - # than it is to try and climb the pom chain here. - if ($Dir.BaseName -eq 'cosmos') - { - $clientArr += $artifactId - } - else - { - Write-Host "*snowflake* Pom $PomPath, has a null or empty relative path." - } - } - else - { - if (($parent.IndexOf('pom.client.xml') -ne -1) -or ($parent.IndexOf('pom.data.xml') -ne -1)) - { - $clientArr += $artifactId - } - else - { - $mgmtArr += $artifactId - } - } - } - } - # Only create this if there's something to create - #if (($clientArr.Count -gt 0) -or ($mgmtArr.Count -gt 0)) - if ($clientArr.Count -gt 0) - { - New-Item -Path $YmlPath -Name "$($Dir.Name).md" -Force - Add-Content -Path "$($YmlPath)/toc.yml" -Value "- name: $($mappedDir)`r`n href: $($Dir.Name).md" - # loop through the arrays and add the appropriate artifacts under the appropriate headings - if ($clientArr.Count -gt 0) - { - Add-Content -Path "$($YmlPath)/$($Dir.Name).md" -Value "# Client Libraries" - foreach($lib in $clientArr) - { - Write-Host "Write $($lib) to $($Dir.Name).md" - Add-Content -Path "$($YmlPath)/$($Dir.Name).md" -Value "#### $lib" - } - } - # For the moment there are no management docs and with the way some of the libraries - # in management are versioned is a bit wonky. They aren't versioned by releasing a new - # version with the same groupId/artifactId, they're versioned with the same artifactId - # and version with a different groupId and the groupId happens to include the date. For - # example, the artifact/version of azure-mgmt-storage:1.0.0-beta has several different - # groupIds. com.microsoft.azure.storage.v2016_01_01, com.microsoft.azure.storage.v2017_10_01, - # com.microsoft.azure.storage.v2018_11_01 etc. - #if ($mgmtArr.Count -gt 0) - #{ - # Add-Content -Path "$($YmlPath)/$($Dir.Name).md" -Value "# Management Libraries" - # foreach($lib in $mgmtArr) - # { - # Write-Output "Write $($lib) to $($Dir.Name).md" - # Add-Content -Path "$($YmlPath)/$($Dir.Name).md" -Value "#### $lib" - # } - #} - } - } - - New-Item -Path "$(Build.SourcesDirectory)/docfx_project" -Name "toc.yml" -Force - Add-Content -Path "$(Build.SourcesDirectory)/docfx_project/toc.yml" -Value "- name: Azure SDK for Java APIs`r`n href: api/`r`n homepage: api/index.md" - Copy-Item "$(Build.SourcesDirectory)/README.md" -Destination "$(Build.SourcesDirectory)/docfx_project/api/index.md" -Force - displayName: Create main index and navigation toc.yml, copy over readme. - - pwsh: ls - workingDirectory: $(Build.SourcesDirectory)/docfx_project/api - - task: CmdLine@2 - displayName: Build Doc Content - inputs: - script: $(Build.BinariesDirectory)/docfx/docfx.exe build - workingDirectory: $(Build.SourcesDirectory)/docfx_project/ - failOnStderr: true - pwsh: | - Copy-Item "$(Build.SourcesDirectory)/eng/docgeneration/assets/*" -Destination "$(Build.SourcesDirectory)/docfx_project/_site/" -Force - displayName: Replace site assets + $(Build.SourcesDirectory)/eng/docgeneration/Generate-DocIndex.ps1 -RepoRoot $(Build.SourcesDirectory) -DocGenDir "$(Build.SourcesDirectory)/eng/docgeneration" -verbose + displayName: 'Generate Doc Index' + - task: UsePythonVersion@0 displayName: 'Use Python 3.6' inputs: diff --git a/eng/spotbugs-aggregate-report/pom.xml b/eng/spotbugs-aggregate-report/pom.xml index b4a8ae359e20a..36dc403cad51c 100644 --- a/eng/spotbugs-aggregate-report/pom.xml +++ b/eng/spotbugs-aggregate-report/pom.xml @@ -67,6 +67,8 @@ ..\..\sdk\storage\azure-storage-blob-batch\src\samples\java\com ..\..\sdk\storage\azure-storage-blob-cryptography\src\main\java\com ..\..\sdk\storage\azure-storage-blob-cryptography\src\samples\java\com + ..\..\sdk\storage\azure-storage-blob-nio\src\main\java\com + ..\..\sdk\storage\azure-storage-blob-nio\src\samples\java\com ..\..\sdk\storage\azure-storage-file-share\src\main\java\com ..\..\sdk\storage\azure-storage-file-share\src\samples\java\com ..\..\sdk\storage\azure-storage-file-datalake\src\main\java\com @@ -153,27 +155,27 @@ com.azure azure-data-appconfiguration - 1.0.0-beta.8 + 1.0.1 com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 com.azure azure-core-amqp - 1.0.0-beta.9 + 1.0.1 com.azure azure-core-http-netty - 1.2.0-beta.1 + 1.3.0-beta.1 com.azure azure-core-http-okhttp - 1.1.0-beta.1 + 1.2.0-beta.1 + 1.2.0-beta.1 com.azure azure-core-tracing-opencensus - 1.0.0-beta.6 + 1.0.0-beta.7 com.azure azure-messaging-eventhubs - 5.0.0-beta.7 + 5.0.1 com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.0.0-beta.5 + 1.0.1 com.azure @@ -208,42 +210,47 @@ com.azure azure-security-keyvault-certificates - 4.0.0-beta.8 + 4.0.0 com.azure azure-security-keyvault-keys - 4.1.0-beta.1 + 4.1.0 com.azure azure-security-keyvault-secrets - 4.1.0-beta.1 + 4.1.0 com.azure azure-storage-common - 12.2.0-beta.2 + 12.2.0 com.azure azure-storage-blob - 12.2.0-beta.2 + 12.2.0 com.azure azure-storage-blob-batch - 12.2.0-beta.1 + 12.2.0 com.azure azure-storage-blob-cryptography - 12.2.0-beta.1 + 12.2.0 + + + com.azure + azure-storage-blob-nio + 12.0.0-beta.1 com.azure azure-storage-file-share - 12.1.0-beta.2 + 12.1.0 com.azure @@ -253,7 +260,7 @@ com.azure azure-storage-queue - 12.2.0-beta.2 + 12.2.0 + 1.6.0 ./parent/pom.xml diff --git a/sdk/appconfiguration/azure-data-appconfiguration/CHANGELOG.md b/sdk/appconfiguration/azure-data-appconfiguration/CHANGELOG.md index 19c7d929059cb..805912b51469a 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/CHANGELOG.md +++ b/sdk/appconfiguration/azure-data-appconfiguration/CHANGELOG.md @@ -1,10 +1,16 @@ # Release History -## 1.0.0-beta.8 (Unreleased) +## 1.0.1 (2020-01-07) +- Added support for setting `x-ms-client-request-id`, `x-ms-correlation-request-id` and `correlation-context` http header values. +- Fixed `UserAgent` unknown name and unknown version bug. +- Fixed `connectionString()`, it throws `IllegalArgumentException` error when `connectionString` is an empty string, + the secret contained within the connection string is invalid or the HMAC-SHA256 MAC algorithm cannot be instantiated. +- No longer set `TokenCredential` to null when `connectionString` is given, or visa versa. -## 1.0.0-preview.7 (2019-11-26) -For details on the Azure SDK for Java (November 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview7-java). +### Breaking changes +- SettingSelector takes a filter instead of taking a list of strings. Supported `SettingSelector` literal special character and wild card functions. +## 1.0.0-beta.7 (2019-11-26) - Added support for Azure Activity Directory authentication. - Added service API version support @@ -13,7 +19,6 @@ For details on the Azure SDK for Java (November 2019 Preview) release refer to t - Removed Range class, SettingSelector no longer supports Range. ## 1.0.0-preview.6 (2019-10-31) -For details on the Azure SDK for Java (October 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview6-java). - Renamed addSetting, getSetting, deleteSetting, setSetting, listSettings, listSettingRevisions to addConfigurationSetting, getConfigurationSetting, deleteConfigurationSetting, setConfigurationSetting, listConfigurationSettings, listRevisions for consistency naming across languages. @@ -30,8 +35,6 @@ and [samples](https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration) ## 1.0.0-preview.5 (2019-10-11) -For details on the Azure SDK for Java (September 2019 Preview) release refer to the [release announcement](https://azure.github.io/azure-sdk/releases/2019-10-11/java.html). - - Fixed a explored bug that ConfigurationClientCredential is already pacakge-private. Using connection String instead. This package's @@ -41,8 +44,6 @@ and demonstrate the new API. ## 1.0.0-preview.4 (2019-10-8) -For details on the Azure SDK for Java (October 2019 Preview) release refer to the [release announcement](https://azure.github.io/azure-sdk/releases/2019-10-11/java.html). - - Updated addSetting, getSetting, deleteSetting, setSetting to support conditional request. - Removed UpdateSetting. - Allowed user to define custom equality of configuration setting. @@ -56,8 +57,6 @@ and demonstrate the new API. ## 1.0.0-preview.3 (2019-09-10) -For details on the Azure SDK for Java (September 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview3-java). - - Removed dependency on Netty. - Added logging when throwing `RutimeException`s. @@ -68,8 +67,6 @@ and demonstrate the new API. ## 1.0.0-preview.2 (2019-08-06) -For details on the Azure SDK for Java (August 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview2-java). - - Merged ConfigurationClientBuilder and ConfigurationAsyncClientBuilder into ConfigurationClientBuilder. Method to build each client were added. - ConfigurationClientBuilder was made instantiable, static builder method removed from ConfigurationClient and ConfigurationAsyncClient. - Builder method credentials renamed to credential and serviceEndpoint to endpoint. @@ -91,8 +88,6 @@ Version 1.0.0-preview.1 is a preview of our efforts in creating a client library to the Java ecosystem, and as consistent across different languages and platforms as possible. The principles that guide our efforts can be found in the [Azure SDK Design Guidelines for Java](https://azure.github.io/azure-sdk/java_introduction.html). -For details on the Azure SDK for Java (July 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview1-java). - This package's [documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-data-appconfiguration_1.0.0-preview.1/appconfiguration/client/README.md) and diff --git a/sdk/appconfiguration/azure-data-appconfiguration/README.md b/sdk/appconfiguration/azure-data-appconfiguration/README.md index 52820c3b0f3af..cca9820f33542 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/README.md +++ b/sdk/appconfiguration/azure-data-appconfiguration/README.md @@ -23,7 +23,7 @@ Use the client library for App Configuration to create and manage application co com.azure azure-data-appconfiguration - 1.0.0-preview.6 + 1.0.1 ``` [//]: # ({x-version-update-end}) @@ -37,7 +37,7 @@ AppConfiguration to use Netty HTTP client. com.azure azure-core-http-netty - 1.0.0 + 1.2.0 ``` [//]: # ({x-version-update-end}) @@ -52,7 +52,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-data-appconfiguration - 1.0.0-preview.6 + 1.0.1 com.azure @@ -67,7 +67,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-core-http-okhttp - 1.0.0 + 1.1.0 ``` [//]: # ({x-version-update-end}) @@ -77,6 +77,7 @@ When an HTTP client is included on the classpath, as shown above, it is not nece For starters, by having the Netty or OkHTTP dependencies on your classpath, as shown above, you can create new instances of these `HttpClient` types using their builder APIs. For example, here is how you would create a Netty HttpClient instance: + ```java HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) @@ -107,7 +108,9 @@ az appconfig create --name --resource-group Alternatively, get the connection string from the Azure Portal. -#### Create a Configuration Client +##### Create a Configuration Client Once you have the value of the connection string you can create the configuration client: + ```Java -ConfigurationClient client = new ConfigurationClientBuilder() - .connectionString(connectionString) - .buildClient(); +ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); ``` or + ```Java -ConfigurationAsyncClient client = new ConfigurationClientBuilder() - .connectionString(connectionString) - .buildAsyncClient(); +ConfigurationAsyncClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); ``` -You can also use `TokenCredential` to create a configuration client, such as an Azure Active Directory (AAD) token. -Unlike a connection string if you're using an AAD token you must supply the endpoint of AppConfiguration service. The -endpoint can be obtained by going to your App Configuration instance in the Azure portal and navigating to "Overview" -page and look for the "Endpoint" keyword. +#### Use AAD token -```Java -// An example of using TokenCredential and Endpoint to create a synchronous client -TokenCredential credential = new DefaultAzureCredential(); +Here we demonstrate using [DefaultAzureCredential][default_cred_ref] +to authenticate as a service principal. However, the configuration client +accepts any [azure-identity][azure_identity] credential. See the +[azure-identity][azure_identity] documentation for more information about other +credentials. + +##### Create a service principal (optional) +This [Azure CLI][azure_cli] snippet shows how to create a +new service principal. Before using it, replace "your-application-name" with +the appropriate name for your service principal. + +Create a service principal: +```Bash +az ad sp create-for-rbac --name http://my-application --skip-assignment +``` + +Output: +```json + { + "appId": "generated app id", + "displayName": "my-application", + "name": "http://my-application", + "password": "random password", + "tenant": "tenant id" + } +``` + +Use the output to set **AZURE_CLIENT_ID** ("appId" above), **AZURE_CLIENT_SECRET** +("password" above) and **AZURE_TENANT_ID** ("tenant" above) environment variables. +The following example shows a way to do this in Bash: +```Bash +export AZURE_CLIENT_ID="generated app id" +export AZURE_CLIENT_SECRET="random password" +export AZURE_TENANT_ID="tenant id" +``` -ConfigurationClient client = new ConfigurationClientBuilder() - .credential(credential) - .endpoint(endpoint) - .buildClient(); +Assign one of the applicable [App Configuration roles][app_config_role] to the service principal. + +##### Create a client +Once the **AZURE_CLIENT_ID**, **AZURE_CLIENT_SECRET** and +**AZURE_TENANT_ID** environment variables are set, +[DefaultAzureCredential][default_cred_ref] will be able to authenticate the +configuration client. + +Constructing the client also requires your configuration store's URL, which you can +get from the Azure CLI or the Azure Portal. In the Azure Portal, the URL can be found listed as the service "Endpoint" + + +```Java +DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); +ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .credential(credential) + .endpoint(endpoint) + .buildClient(); ``` ## Key concepts @@ -164,30 +212,39 @@ The client performs the interactions with the App Configuration service, getting An application that needs to retrieve startup configurations is better suited using the synchronous client, for example setting up a SQL connection. + ```Java -ConfigurationClient client = new ConfigurationClientBuilder() - .connectionString(connectionString) - .buildClient(); +ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); // urlLabel is optional -String url = client.getConfigurationSetting(urlKey, urlLabel).getValue(); -Connection conn; +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); + } + } } - ``` An application that has a large set of configurations that it needs to periodically update is be better suited using the asynchronous client, for example all settings with a specific label are periodically updated. + ```Java -ConfigurationAsyncClient client = new ConfigurationClientBuilder() - .connectionString(appConfigConnectionString) - .buildAsyncClient(); +ConfigurationAsyncClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); -client.listConfigurationSettings(new SettingSelector().setLabels(periodicUpdateLabel)) +configurationClient.listConfigurationSettings(new SettingSelector().setLabelFilter(periodicUpdateLabel)) .subscribe(setting -> updateConfiguration(setting)); ``` @@ -198,10 +255,12 @@ The following sections provide several code snippets covering some of the most c ### Create a Configuration Client Create a configuration client by using `ConfigurationClientBuilder` by passing connection string. + + ```Java -ConfigurationClient client = new ConfigurationClientBuilder() - .connectionString(connectionString) - .buildClient(); +ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); ``` ### Create a Configuration Setting @@ -209,96 +268,127 @@ ConfigurationClient client = new ConfigurationClientBuilder() Create a configuration setting to be stored in the configuration store. There are two ways to store a configuration setting: - `addConfigurationSetting` creates a setting only if the setting does not already exist in the store. + + ```Java ConfigurationSetting setting = configurationClient.addConfigurationSetting("new_key", "new_label", "new_value"); ``` + Or + - `setConfigurationSetting` creates a setting if it doesn't exist or overrides an existing setting. + + ```Java -ConfigurationSetting setting = client.setConfigurationSetting("some_key", "some_label", "some_value"); +ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); ``` ### Retrieve a Configuration Setting Retrieve a previously stored configuration setting by calling `getConfigurationSetting`. + + ```Java -ConfigurationSetting setting = client.setConfigurationSetting("some_key", "some_label", "some_value"); -ConfigurationSetting retrievedSetting = client.getConfigurationSetting("some_key", "some_label"); +ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); +ConfigurationSetting retrievedSetting = configurationClient.getConfigurationSetting("some_key", "some_label"); ``` + For conditional request, if you want to conditionally fetch a configuration setting, set `ifChanged` to true. When `ifChanged` is true, the configuration setting is only retrieved if it is different than the given `setting`. This is determined by comparing the ETag of the `setting` to the one in the service to see if they are the same or not. If the ETags are not the same, it means the configuration setting is different, and its value is retrieved. + + ```Java -Response settingResponse = client.getConfigurationSettingWithResponse(setting, null, true, Context.NONE); +ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); +Response settingResponse = configurationClient.getConfigurationSettingWithResponse(setting, null, true, Context.NONE); ``` ### Update an existing Configuration Setting Update an existing configuration setting by calling `setConfigurationSetting`. + + ```Java -ConfigurationSetting setting = client.setConfigurationSetting("some_key", "some_label", "some_value"); -ConfigurationSetting updatedSetting = client.setConfigurationSetting("some_key", "some_label", "new_value"); +ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); +ConfigurationSetting updatedSetting = configurationClient.setConfigurationSetting("some_key", "some_label", "new_value"); ``` + For conditional request, if you want to conditionally update a configuration setting, set the `ifUnchanged` parameter to true. When `ifUnchanged` is true, the configuration setting is only updated if it is same as the given `setting`. This is determined by comparing the ETag of the `setting` to the one in the service to see if they are the same or not. If the ETag are the same, it means the configuration setting is same, and its value is updated. + + ```Java -Response settingResponse = client.setConfigurationSettingWithResponse(setting, true, Context.NONE); +ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); +Response settingResponse = configurationClient.setConfigurationSettingWithResponse(setting, true, Context.NONE); ``` ### Delete a Configuration Setting Delete an existing configuration setting by calling `deleteConfigurationSetting`. + + ```Java -ConfigurationSetting setting = client.setConfigurationSetting("some_key", "some_label", "some_value"); -ConfigurationSetting deletedSetting = client.deleteConfigurationSetting("some_key", "some_label"); +ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); +ConfigurationSetting deletedSetting = configurationClient.deleteConfigurationSetting("some_key", "some_label"); ``` For conditional request, if you want to conditionally delete a configuration setting, set the `ifUnchanged` parameter to true. When `ifUnchanged` parameter to true. When `ifUnchanged` is true, the configuration setting is only deleted if it is same as the given `setting`. This is determined by comparing the ETag of the `setting` to the one in the service to see if they are the same or not. If the ETag are same, it means the configuration setting is same, and its value is deleted. + + ```Java -Response settingResponse = client.deleteConfigurationSettingWithResponse(setting, true, Context.NONE); +ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); +Response settingResponse = configurationClient.deleteConfigurationSettingWithResponse(setting, true, Context.NONE); ``` ### List Configuration Settings with multiple keys List multiple configuration settings by calling `listConfigurationSettings`. Pass a null `SettingSelector` into the method if you want to fetch all the configuration settings and their fields. + + ```Java String key = "some_key"; String key2 = "new_key"; -client.setConfigurationSetting(key, "some_label", "some_value"); -client.setConfigurationSetting(key2, "new_label", "new_value"); -SettingSelector selector = new SettingSelector().setKeys(key, key2); -PagedIterable settings = client.listConfigurationSettings(selector); +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); ``` ### List revisions of multiple Configuration Settings List all revisions of a configuration setting by calling `listRevisions`. + + ```Java String key = "revisionKey"; -client.setConfigurationSetting(key, "some_label", "some_value"); -client.setConfigurationSetting(key, "new_label", "new_value"); -SettingSelector selector = new SettingSelector().setKeys(key); -PagedIterable settings = client.listRevisions(selector); +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); ``` ### Set a Configuration Setting to read only Set a configuration setting to read-only status. + + ```Java -client.setConfigurationSetting("some_key", "some_label", "some_value"); -ConfigurationSetting setting = client.setReadOnly("some_key", "some_label", true); +configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); +ConfigurationSetting setting = configurationClient.setReadOnly("some_key", "some_label", true); ``` ### Clear read only from a Configuration Setting Clear read-only from a configuration setting. + + ```Java -ConfigurationSetting setting = client.setReadOnly("some_key", "some_label", false); +ConfigurationSetting setting = configurationClient.setReadOnly("some_key", "some_label", false); ``` ## Troubleshooting @@ -309,17 +399,18 @@ When you interact with App Configuration using this Java client library, errors App Configuration provides a way to define customized headers through `Context` object in the public API. + ```java - // Add your headers - HttpHeaders headers = new HttpHeaders(); - headers.put("my-header1", "my-header1-value"); - headers.put("my-header2", "my-header2-value"); - headers.put("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. +// Add your headers +HttpHeaders headers = new HttpHeaders(); +headers.put("my-header1", "my-header1-value"); +headers.put("my-header2", "my-header2-value"); +headers.put("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. ``` For more detail information, check out the [AddHeadersFromContextPolicy][add_headers_from_context_policy] @@ -337,23 +428,26 @@ 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][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments. +[add_headers_from_context_policy]: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AddHeadersFromContextPolicy.java [api_documentation]: https://aka.ms/java-docs [app_config_store]: https://docs.microsoft.com/azure/azure-app-configuration/quickstart-dotnet-core-app#create-an-app-configuration-store +[app_config_role]: https://github.com/Azure/AppConfiguration/blob/master/docs/REST/authorization/aad.md [azconfig_docs]: https://docs.microsoft.com/azure/azure-app-configuration [azure_cli]: https://docs.microsoft.com/cli/azure +[azure_identity]: https://github.com/Azure/azure-sdk-for-java/tree/master/sdk/identity/azure-identity [azure_subscription]: https://azure.microsoft.com/free [cla]: https://cla.microsoft.com [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com +[default_cred_ref]: https://azuresdkdocs.blob.core.windows.net/$web/java/azure-identity/1.0.1/com/azure/identity/DefaultAzureCredential.html [maven]: https://maven.apache.org/ [package]: https://search.maven.org/artifact/com.azure/azure-data-appconfiguration +[performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning [rest_api]: https://github.com/Azure/AppConfiguration#rest-api-reference [samples]: src/samples/java/com/azure/data/appconfiguration [samples_readme]: src/samples/README.md [source_code]: src [spring_quickstart]: https://docs.microsoft.com/azure/azure-app-configuration/quickstart-java-spring-app -[performance_tuning]: https://github.com/Azure/azure-sdk-for-java/wiki/Performance-Tuning -[add_headers_from_context_policy]: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/AddHeadersFromContextPolicy.java ![Impressions](https://azure-sdk-impressions.azurewebsites.net/api/impressions/azure-sdk-for-java%2Fsdk%2Fappconfiguration%2Fazure-data-appconfiguration%2FREADME.png) diff --git a/sdk/appconfiguration/azure-data-appconfiguration/pom.xml b/sdk/appconfiguration/azure-data-appconfiguration/pom.xml index b560c9da4089f..d968637ada1f4 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/pom.xml +++ b/sdk/appconfiguration/azure-data-appconfiguration/pom.xml @@ -13,7 +13,7 @@ com.azure azure-data-appconfiguration - 1.0.0-beta.8 + 1.0.1 Microsoft Azure client library for App Configuration This package contains the Microsoft Azure App Configuration client library. @@ -36,7 +36,7 @@ com.azure azure-core - 1.2.0-beta.1 + 1.2.0 org.slf4j @@ -46,14 +46,14 @@ com.azure azure-core-http-netty - 1.1.0 + 1.2.0 com.azure azure-core-test - 1.1.0-beta.1 + 1.1.0 test @@ -95,7 +95,7 @@ com.azure azure-identity - 1.0.1 + 1.0.2 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 87b95161cf56a..f51c0e273634a 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 @@ -214,7 +214,7 @@ public Mono setConfigurationSetting(String key, String lab */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setConfigurationSettingWithResponse(ConfigurationSetting setting, - boolean ifUnchanged) { + boolean ifUnchanged) { try { return withContext(context -> setConfigurationSetting(setting, ifUnchanged, context)); } catch (RuntimeException ex) { @@ -223,7 +223,7 @@ public Mono> setConfigurationSettingWithResponse( } Mono> setConfigurationSetting(ConfigurationSetting setting, boolean ifUnchanged, - Context context) { + Context context) { // Validate that setting and key is not null. The key is used in the service URL so it cannot be null. validateSetting(setting); @@ -324,8 +324,7 @@ public Mono getConfigurationSetting(String key, String lab */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> getConfigurationSettingWithResponse(ConfigurationSetting setting, - OffsetDateTime acceptDateTime, - boolean ifChanged) { + OffsetDateTime acceptDateTime, boolean ifChanged) { try { return withContext(context -> getConfigurationSetting(setting, acceptDateTime, ifChanged, context)); } catch (RuntimeException ex) { @@ -334,9 +333,7 @@ public Mono> getConfigurationSettingWithResponse( } Mono> getConfigurationSetting(ConfigurationSetting setting, - OffsetDateTime acceptDateTime, - boolean onlyIfChanged, - Context context) { + OffsetDateTime acceptDateTime, boolean onlyIfChanged, Context context) { // Validate that setting and key is not null. The key is used in the service URL so it cannot be null. validateSetting(setting); @@ -419,7 +416,7 @@ public Mono deleteConfigurationSetting(String key, String */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> deleteConfigurationSettingWithResponse(ConfigurationSetting setting, - boolean ifUnchanged) { + boolean ifUnchanged) { try { return withContext(context -> deleteConfigurationSetting(setting, ifUnchanged, context)); } catch (RuntimeException ex) { @@ -428,7 +425,7 @@ public Mono> deleteConfigurationSettingWithRespon } Mono> deleteConfigurationSetting(ConfigurationSetting setting, boolean ifUnchanged, - Context context) { + Context context) { // Validate that setting and key is not null. The key is used in the service URL so it cannot be null. validateSetting(setting); final String ifMatchETag = ifUnchanged ? getETagValue(setting.getETag()) : null; @@ -498,7 +495,7 @@ public Mono setReadOnly(String key, String label, boolean */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono> setReadOnlyWithResponse(ConfigurationSetting setting, - boolean isReadOnly) { + boolean isReadOnly) { try { return withContext(context -> setReadOnly(setting, isReadOnly, context)); } catch (RuntimeException ex) { @@ -507,7 +504,7 @@ public Mono> setReadOnlyWithResponse(Configuratio } Mono> setReadOnly(ConfigurationSetting setting, boolean isReadOnly, - Context context) { + Context context) { // Validate that setting and key is not null. The key is used in the service URL so it cannot be null. validateSetting(setting); 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 b4d1ad18e5e1a..fb8d39df2453d 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 @@ -67,7 +67,7 @@ * @see ConfigurationAsyncClient * @see ConfigurationClient */ -@ServiceClientBuilder(serviceClients = ConfigurationClient.class) +@ServiceClientBuilder(serviceClients = {ConfigurationAsyncClient.class, ConfigurationClient.class}) public final class ConfigurationClientBuilder { // This header tells the server to return the request id in the HTTP response. Useful for correlation with what @@ -239,25 +239,30 @@ public ConfigurationClientBuilder endpoint(String endpoint) { * @param connectionString Connection string in the format "endpoint={endpoint_value};id={id_value}; * secret={secret_value}" * @return The updated ConfigurationClientBuilder object. - * @throws NullPointerException If {@code credential} is {@code null}. + * @throws NullPointerException If {@code connectionString} is {@code null}. + * @throws IllegalArgumentException if {@code connectionString} is an empty string, the {@code connectionString} + * secret is invalid, or the HMAC-SHA256 MAC algorithm cannot be instantiated. */ public ConfigurationClientBuilder connectionString(String connectionString) { - Objects.requireNonNull(connectionString); + Objects.requireNonNull(connectionString, "'connectionString' cannot be null."); + + if (connectionString.isEmpty()) { + throw logger.logExceptionAsError( + new IllegalArgumentException("'connectionString' cannot be an empty string.")); + } try { this.credential = new ConfigurationClientCredentials(connectionString); } catch (InvalidKeyException err) { throw logger.logExceptionAsError(new IllegalArgumentException( - "The secret is invalid and cannot instantiate the HMAC-SHA256 algorithm.", err)); + "The secret contained within the connection string is invalid and cannot instantiate the HMAC-SHA256" + + " algorithm.", err)); } catch (NoSuchAlgorithmException err) { throw logger.logExceptionAsError( new IllegalArgumentException("HMAC-SHA256 MAC algorithm cannot be instantiated.", err)); } this.endpoint = credential.getBaseUri(); - - // Clear TokenCredential in favor of connection string credential - this.tokenCredential = null; return this; } @@ -272,9 +277,6 @@ public ConfigurationClientBuilder credential(TokenCredential tokenCredential) { // token credential can not be null value Objects.requireNonNull(tokenCredential); this.tokenCredential = tokenCredential; - - // Clear connection string based credential in favor of TokenCredential - this.credential = null; return this; } diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/README.md b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/README.md index 7c648a01bcefd..cde109a068f8c 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/README.md +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/README.md @@ -20,7 +20,7 @@ Maven dependency for Azure app configuration Client library. Add it to your proj com.azure azure-data-appconfiguration - 1.0.0-preview.6 + 1.0.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/AadAuthentication.java b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/AadAuthentication.java index cbe209e47f671..4a6e18f540967 100644 --- a/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/AadAuthentication.java +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/AadAuthentication.java @@ -3,8 +3,8 @@ package com.azure.data.appconfiguration; -import com.azure.core.credential.TokenCredential; import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.identity.DefaultAzureCredential; import com.azure.identity.DefaultAzureCredentialBuilder; /** @@ -21,9 +21,13 @@ public static void main(String[] args) { // and navigating to "Overview" page. Looking for the "Endpoint" keyword. String endpoint = "{endpoint_value}"; - // Token Credential could be an AAD token which you can get from Identity - // or other service authentication service. - TokenCredential tokenCredential = new DefaultAzureCredentialBuilder().build(); + // 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 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 new file mode 100644 index 0000000000000..ee4c240675b00 --- /dev/null +++ b/sdk/appconfiguration/azure-data-appconfiguration/src/samples/java/com/azure/data/appconfiguration/ReadmeSamples.java @@ -0,0 +1,175 @@ +// 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.HttpHeaders; +import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; +import com.azure.core.http.policy.AddHeadersFromContextPolicy; +import com.azure.core.http.rest.PagedIterable; +import com.azure.core.http.rest.Response; +import com.azure.core.util.Context; +import com.azure.data.appconfiguration.models.ConfigurationSetting; +import com.azure.data.appconfiguration.models.SettingSelector; +import com.azure.identity.DefaultAzureCredential; +import com.azure.identity.DefaultAzureCredentialBuilder; + +import java.sql.Connection; +import java.sql.DriverManager; +import java.sql.SQLException; + +/** + * 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 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 createHttpClient() { + HttpClient client = new NettyAsyncHttpClientBuilder() + .port(8080) + .wiretap(true) + .build(); + } + + public void createClient() { + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildClient(); + } + + public void createAsyncClient() { + ConfigurationAsyncClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + } + + public void aadAuthentication() { + DefaultAzureCredential credential = new DefaultAzureCredentialBuilder().build(); + ConfigurationClient configurationClient = new ConfigurationClientBuilder() + .credential(credential) + .endpoint(endpoint) + .buildClient(); + } + + public void 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); + } + } + } + } + + public void listConfigurationsExample() { + ConfigurationAsyncClient configurationClient = new ConfigurationClientBuilder() + .connectionString(connectionString) + .buildAsyncClient(); + + configurationClient.listConfigurationSettings(new SettingSelector().setLabelFilter(periodicUpdateLabel)) + .subscribe(setting -> updateConfiguration(setting)); + } + + public void addConfigurationSetting() { + ConfigurationSetting setting = configurationClient.addConfigurationSetting("new_key", "new_label", "new_value"); + } + + public void setConfigurationSetting() { + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + } + + public void getConfigurationSetting() { + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting retrievedSetting = configurationClient.getConfigurationSetting("some_key", "some_label"); + } + + public void getConfigurationSettingConditionally() { + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + Response settingResponse = configurationClient.getConfigurationSettingWithResponse(setting, null, true, Context.NONE); + } + + public void updateConfigurationSetting() { + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting updatedSetting = configurationClient.setConfigurationSetting("some_key", "some_label", "new_value"); + } + + public void updateConfigurationSettingConditionally() { + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + Response settingResponse = configurationClient.setConfigurationSettingWithResponse(setting, true, Context.NONE); + } + + public void deleteConfigurationSetting() { + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting deletedSetting = configurationClient.deleteConfigurationSetting("some_key", "some_label"); + } + + public void deleteConfigurationSettingConditionally() { + ConfigurationSetting setting = configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + Response settingResponse = configurationClient.deleteConfigurationSettingWithResponse(setting, true, Context.NONE); + } + + public void 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); + } + + public void 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); + } + + public void setReadOnly() { + configurationClient.setConfigurationSetting("some_key", "some_label", "some_value"); + ConfigurationSetting setting = configurationClient.setReadOnly("some_key", "some_label", true); + } + + public void clearReadOnly() { + ConfigurationSetting setting = configurationClient.setReadOnly("some_key", "some_label", false); + } + + public void customHeaders() { + // Add your headers + HttpHeaders headers = new HttpHeaders(); + headers.put("my-header1", "my-header1-value"); + headers.put("my-header2", "my-header2-value"); + headers.put("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. + } + + private void updateConfiguration(ConfigurationSetting setting) { + // do something on the given setting. + } +} diff --git a/sdk/core/azure-core-amqp/CHANGELOG.md b/sdk/core/azure-core-amqp/CHANGELOG.md new file mode 100644 index 0000000000000..14f7ad7a1365d --- /dev/null +++ b/sdk/core/azure-core-amqp/CHANGELOG.md @@ -0,0 +1,61 @@ +# Release History + +## 1.0.1 (2020-01-07) +- Client library name and version are no longer hard coded in connection properties. +- Update qpid-proton-j-extensions dependency +- Shorten tracing span names + +## 1.0.0-beta.8 (12-03-2019) +- Changed preview to beta. +- Fixes authorization when using client credentials. +- Changed FullyQualifiedDomainName -> FullyQualifiedNamespace. +- Renamed `BatchOptions` -> `CreateBatchOptions` and added `getRetryMode`. +- Renamed `ProxyConfiguration` -> `ProxyOption`s. +- Removed cloneable from retry policies. +- Renamed `RetryOptions`, `RetryPolicy` -> `AmqpRetryOptions`, `AmqpRetryPolicy`. +- Updated `RetryMode` -> `AmqpRetryMode`. +- Updated CBS -> ClaimsBasedSecurityNode. +- Removed final from RetryPolicy. +- Updated Hostname -> FullyQualifiedNamespace. +- `AmqpConnection` implements AutoCloseable. Added `getEndpointStates` API. +- `AmqpConnection`/`Link`/`Session` implements AutoCloseable. Added `getEndpointStates` API. +- `CBSNode` implements AutoCloseable. +- Deleted EndpointStateNotifier. Added ShutdownSignals to Connection. +- Deleted EndpointStateNotifierBase. +- Updated parameter name for MessageConstant.fromValue. +- Moved AmqpExceptionHandler into implementation class. +- Updated CBS -> Cbs. +- Added `AmqpEndpointStateUtil`. +- Closed ReactorReceiver on errors or closures in link. + +## 1.0.0-preview.7 (2019-11-04) + +## 1.0.0-preview.6 (2019-10-10) +- Added more error messages for checking null. + +## 1.0.0-preview.5 (2019-10-07) +- Getters and setters were updated to use Java Bean notation. +- Added `MessageSerializer` to azure-core-amqp. +- Moved Reactor handlers into azure-core-amqp. +- Moved implementation specific classes to azure-core-amqp. +- Moved ReactorDispatcher, AmqpErrorCode to azure-core-amqp. +- Renamed `getIdentifier` to `getId`. +- Renamed `getHost` to `getHostName`. +- Cleanup and introduced OpenCensus Tracing plugin. +- Added `PROTON_IO` in ErrorCondition. +- Added `ProxyConfiguration` for API `createConnectionHandler`. + +## 1.0.0-preview.4 (2019-09-09) +- Support tracing for azure-core-amqp. + +## 1.0.0-preview.3 (2019-08-05) +- Retry implements Cloneable. +- Rename `Retry` to `RetryPolicy`. +- `RetryOptions` implements Cloneable. + +## 1.0.0-preview.2 (2019-07-02) + +## 1.0.0-preview.1 (2019-06-28) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-core-amqp_1.0.0-preview.1/core/azure-core-amqp/README.md) + diff --git a/sdk/core/azure-core-amqp/README.md b/sdk/core/azure-core-amqp/README.md index cdb69bc11a9b8..76ebaeac91bcf 100644 --- a/sdk/core/azure-core-amqp/README.md +++ b/sdk/core/azure-core-amqp/README.md @@ -16,7 +16,7 @@ own AMQP client library that abstracts from the underlying transport library's i com.azure azure-core-amqp - 1.0.0-preview.7 + 1.0.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-amqp/pom.xml b/sdk/core/azure-core-amqp/pom.xml index 696aa3bbd3af5..1a6bacee37e59 100644 --- a/sdk/core/azure-core-amqp/pom.xml +++ b/sdk/core/azure-core-amqp/pom.xml @@ -13,7 +13,7 @@ com.azure azure-core-amqp - 1.0.0-beta.9 + 1.0.1 jar Microsoft Azure Java Core AMQP Library @@ -57,7 +57,7 @@ com.azure azure-core - 1.2.0-beta.1 + 1.2.0 com.microsoft.azure diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpRetryPolicy.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpRetryPolicy.java index 4a5a2c250b466..f086783a861a5 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpRetryPolicy.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/AmqpRetryPolicy.java @@ -69,7 +69,7 @@ public int getMaxRetries() { * @return The amount of time to delay before retrying the associated operation; if {@code null}, then the operation * is no longer eligible to be retried. */ - public Duration calculateRetryDelay(Exception lastException, int retryCount) { + public Duration calculateRetryDelay(Throwable lastException, int retryCount) { if (retryOptions.getDelay() == Duration.ZERO || retryOptions.getMaxDelay() == Duration.ZERO || retryCount > retryOptions.getMaxRetries()) { @@ -138,7 +138,7 @@ public boolean equals(Object obj) { * @param exception An exception that was observed for the operation to be retried. * @return true if the exception is a retriable exception, otherwise false. */ - private static boolean isRetriableException(Exception exception) { + private static boolean isRetriableException(Throwable exception) { return (exception instanceof AmqpException) && ((AmqpException) exception).isTransient(); } } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java index f9ff21755852a..4174c9e1b10f7 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ActiveClientTokenManager.java @@ -8,17 +8,18 @@ import com.azure.core.amqp.exception.AmqpResponseCode; import com.azure.core.exception.AzureException; import com.azure.core.util.logging.ClientLogger; +import reactor.core.Disposable; +import reactor.core.publisher.EmitterProcessor; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; import reactor.core.publisher.Mono; +import reactor.core.publisher.ReplayProcessor; import java.time.Duration; import java.time.OffsetDateTime; import java.time.ZoneOffset; -import java.util.Timer; -import java.util.TimerTask; import java.util.concurrent.atomic.AtomicBoolean; -import java.util.concurrent.atomic.AtomicLong; +import java.util.concurrent.atomic.AtomicReference; /** * Manages the re-authorization of the client to the token audience against the CBS node. @@ -30,27 +31,19 @@ public class ActiveClientTokenManager implements TokenManager { private final Mono cbsNode; private final String tokenAudience; private final String scopes; - private final Timer timer; - private final Flux authorizationResults; - private FluxSink sink; + private final ReplayProcessor authorizationResults = ReplayProcessor.create(1); + private final FluxSink authorizationResultsSink = + authorizationResults.sink(FluxSink.OverflowStrategy.BUFFER); + private final EmitterProcessor durationSource = EmitterProcessor.create(); + private final FluxSink durationSourceSink = durationSource.sink(); + private final AtomicReference lastRefreshInterval = new AtomicReference<>(Duration.ofMinutes(1)); - // last refresh interval in milliseconds. - private AtomicLong lastRefreshInterval = new AtomicLong(); + private volatile Disposable subscription; public ActiveClientTokenManager(Mono cbsNode, String tokenAudience, String scopes) { - this.timer = new Timer(tokenAudience + "-tokenManager"); this.cbsNode = cbsNode; this.tokenAudience = tokenAudience; this.scopes = scopes; - this.authorizationResults = Flux.create(sink -> { - if (hasDisposed.get()) { - sink.complete(); - } else { - this.sink = sink; - } - }); - - lastRefreshInterval.set(Duration.ofMinutes(1).getSeconds() * 1000); } /** @@ -82,15 +75,18 @@ public Mono authorize() { // We want to refresh the token when 90% of the time before expiry has elapsed. final long refreshSeconds = (long) Math.floor(between.getSeconds() * 0.9); + // This converts it to milliseconds final long refreshIntervalMS = refreshSeconds * 1000; - lastRefreshInterval.set(refreshIntervalMS); - // If this is the first time authorize is called, the task will not have been scheduled yet. if (!hasScheduled.getAndSet(true)) { - logger.info("Scheduling refresh token task."); - scheduleRefreshTokenTask(refreshIntervalMS); + logger.info("Scheduling refresh token task"); + + final Duration firstInterval = Duration.ofMillis(refreshIntervalMS); + lastRefreshInterval.set(firstInterval); + authorizationResultsSink.next(AmqpResponseCode.ACCEPTED); + subscription = scheduleRefreshTokenTask(firstInterval); } return refreshIntervalMS; @@ -99,52 +95,51 @@ public Mono authorize() { @Override public void close() { - if (!hasDisposed.getAndSet(true)) { - if (this.sink != null) { - this.sink.complete(); - } - - this.timer.cancel(); + if (hasDisposed.getAndSet(true)) { + return; } - } - private void scheduleRefreshTokenTask(Long refreshIntervalInMS) { - try { - timer.schedule(new RefreshAuthorizationToken(), refreshIntervalInMS); - } catch (IllegalStateException e) { - logger.warning("Unable to schedule RefreshAuthorizationToken task.", e); - hasScheduled.set(false); + authorizationResultsSink.complete(); + durationSourceSink.complete(); + + if (subscription != null) { + subscription.dispose(); } } - private class RefreshAuthorizationToken extends TimerTask { - @Override - public void run() { - logger.info("Refreshing authorization token."); - authorize().subscribe( - (Long refreshIntervalInMS) -> { - - if (hasDisposed.get()) { - logger.info("Token manager has been disposed of. Not rescheduling."); - return; - } - - logger.info("Authorization successful. Refreshing token in {} ms.", refreshIntervalInMS); - sink.next(AmqpResponseCode.ACCEPTED); - - scheduleRefreshTokenTask(refreshIntervalInMS); - }, error -> { - if ((error instanceof AmqpException) && ((AmqpException) error).isTransient()) { - logger.error("Error is transient. Rescheduling authorization task.", error); - scheduleRefreshTokenTask(lastRefreshInterval.get()); - } else { - logger.error("Error occurred while refreshing token that is not retriable. Not scheduling" - + " refresh task. Use ActiveClientTokenManager.authorize() to schedule task again.", error); - hasScheduled.set(false); - } - - sink.error(error); + private Disposable scheduleRefreshTokenTask(Duration initialRefresh) { + // EmitterProcessor can queue up an initial refresh interval before any subscribers are received. + durationSourceSink.next(initialRefresh); + + return Flux.switchOnNext(durationSource.map(Flux::interval)) + .flatMap(delay -> { + logger.info("Refreshing token."); + return authorize(); + }) + .onErrorContinue( + error -> (error instanceof AmqpException) && ((AmqpException) error).isTransient(), + (amqpException, interval) -> { + final Duration lastRefresh = lastRefreshInterval.get(); + + logger.error("Error is transient. Rescheduling authorization task at interval {} ms.", + lastRefresh.toMillis(), amqpException); + durationSourceSink.next(lastRefreshInterval.get()); + }) + .subscribe(interval -> { + logger.info("Authorization successful. Refreshing token in {} ms.", interval); + authorizationResultsSink.next(AmqpResponseCode.ACCEPTED); + + final Duration nextRefresh = Duration.ofMillis(interval); + lastRefreshInterval.set(nextRefresh); + durationSourceSink.next(Duration.ofMillis(interval)); + }, error -> { + logger.error("Error occurred while refreshing token that is not retriable. Not scheduling" + + " refresh task. Use ActiveClientTokenManager.authorize() to schedule task again.", error); + hasScheduled.set(false); + durationSourceSink.complete(); + authorizationResultsSink.error(error); + }, () -> { + logger.info("Completed refresh token task."); }); - } } } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AzureTokenManagerProvider.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AzureTokenManagerProvider.java index b8540e388d86a..ba930e30020a1 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AzureTokenManagerProvider.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/AzureTokenManagerProvider.java @@ -46,6 +46,8 @@ public AzureTokenManagerProvider(CbsAuthorizationType authorizationType, String public TokenManager getTokenManager(Mono cbsNodeMono, String resource) { final String scopes = getResourceString(resource); final String tokenAudience = String.format(Locale.US, TOKEN_AUDIENCE_FORMAT, fullyQualifiedNamespace, resource); + + logger.info("Creating new token manager for audience[{}], scopes[{}]", tokenAudience, scopes); return new ActiveClientTokenManager(cbsNodeMono, tokenAudience, scopes); } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ClientConstants.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ClientConstants.java index b49ac3bb93cae..cfce200c73625 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ClientConstants.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ClientConstants.java @@ -5,10 +5,6 @@ public final class ClientConstants { public static final String NOT_APPLICABLE = "n/a"; - public static final String PRODUCT_NAME = "azsdk-java-eventhubs"; - // {x-version-update-start;com.azure:azure-messaging-eventhubs;current} - public static final String CURRENT_JAVA_CLIENT_VERSION = "5.0.0-beta.7"; - // {x-version-update-end} public static final String PLATFORM_INFO = getOSInformation(); public static final String FRAMEWORK_INFO = getFrameworkInfo(); @@ -17,8 +13,8 @@ public final class ClientConstants { * $/core/azure-core/src/main/java/com/azure/core/http/policy/UserAgentPolicy.java * TODO (conniey): Extract logic from UserAgentPolicy into something we can use here. */ - public static final String USER_AGENT = String.format("%s/%s %s;%s", - PRODUCT_NAME, CURRENT_JAVA_CLIENT_VERSION, System.getProperty("java.version"), PLATFORM_INFO); + public static final String USER_AGENT_TEMPLATE = + "%s/%s " + System.getProperty("java.version") + ";" + PLATFORM_INFO; /** * The default maximum allowable size, in bytes, for a batch to be sent. diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnection.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnection.java index 6a6393482a9d8..9e895e62ebe8e 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnection.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorConnection.java @@ -72,10 +72,13 @@ public class ReactorConnection implements AmqpConnection { * @param reactorProvider Provides proton-j Reactor instances. * @param handlerProvider Provides {@link BaseHandler} to listen to proton-j reactor events. * @param tokenManagerProvider Provides the appropriate token manager to authorize with CBS node. + * @param messageSerializer Serializer to translate objects to and from proton-j {@link Message messages}. + * @param product The name of the product this connection is created for. + * @param clientVersion The version of the client library creating the connection. */ public ReactorConnection(String connectionId, ConnectionOptions connectionOptions, ReactorProvider reactorProvider, ReactorHandlerProvider handlerProvider, TokenManagerProvider tokenManagerProvider, - MessageSerializer messageSerializer) { + MessageSerializer messageSerializer, String product, String clientVersion) { this.connectionOptions = connectionOptions; this.reactorProvider = reactorProvider; @@ -86,7 +89,7 @@ public ReactorConnection(String connectionId, ConnectionOptions connectionOption this.messageSerializer = messageSerializer; this.handler = handlerProvider.createConnectionHandler(connectionId, connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getTransportType(), - connectionOptions.getProxyOptions()); + connectionOptions.getProxyOptions(), product, clientVersion); this.retryPolicy = RetryUtil.getRetryPolicy(connectionOptions.getRetry()); this.connectionMono = Mono.fromCallable(this::getOrCreateConnection) diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorHandlerProvider.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorHandlerProvider.java index 1ebce066d2ddc..408d3f40de941 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorHandlerProvider.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/ReactorHandlerProvider.java @@ -40,22 +40,26 @@ public ReactorHandlerProvider(ReactorProvider provider) { * @param connectionId Identifier associated with this connection. * @param hostname Host for the connection handler. * @param transportType Transport type used for the connection. + * @param proxyOptions The options to use for proxy. + * @param product The name of the product this connection handler is created for. + * @param clientVersion The version of the client library creating the connection handler. * @return A new {@link ConnectionHandler}. */ public ConnectionHandler createConnectionHandler(String connectionId, String hostname, - AmqpTransportType transportType, ProxyOptions proxyOptions) { + AmqpTransportType transportType, ProxyOptions proxyOptions, String product, String clientVersion) { switch (transportType) { case AMQP: - return new ConnectionHandler(connectionId, hostname); + return new ConnectionHandler(connectionId, hostname, product, clientVersion); case AMQP_WEB_SOCKETS: if (proxyOptions != null && proxyOptions.isProxyAddressConfigured()) { - return new WebSocketsProxyConnectionHandler(connectionId, hostname, proxyOptions); + return new WebSocketsProxyConnectionHandler(connectionId, hostname, proxyOptions, product, + clientVersion); } else if (WebSocketsProxyConnectionHandler.shouldUseProxy(hostname)) { logger.info("System default proxy configured for hostname '{}'. Using proxy.", hostname); return new WebSocketsProxyConnectionHandler(connectionId, hostname, - ProxyOptions.SYSTEM_DEFAULTS); + ProxyOptions.SYSTEM_DEFAULTS, product, clientVersion); } else { - return new WebSocketsConnectionHandler(connectionId, hostname); + return new WebSocketsConnectionHandler(connectionId, hostname, product, clientVersion); } default: throw logger.logExceptionAsWarning(new IllegalArgumentException(String.format(Locale.US, diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ConnectionHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ConnectionHandler.java index 1a24abcecc0fe..4ee59700008fc 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ConnectionHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/ConnectionHandler.java @@ -36,41 +36,31 @@ public class ConnectionHandler extends Handler { static final int MAX_FRAME_SIZE = 65536; private final Map connectionProperties; - protected final ClientLogger logger; + private final ClientLogger logger = new ClientLogger(ConnectionHandler.class); /** * Creates a handler that handles proton-j's connection events. * * @param connectionId Identifier for this connection. * @param hostname Hostname of the AMQP message broker to create a connection to. + * @param product The name of the product this connection handler is created for. + * @param clientVersion The version of the client library creating the connection handler. */ - public ConnectionHandler(final String connectionId, final String hostname) { - this(connectionId, hostname, new ClientLogger(ConnectionHandler.class)); - } - - /** - * Creates a handler that handles proton-j's connection events. - * - * @param connectionId Identifier for this connection. - * @param hostname Hostname to use for socket creation. If there is a proxy configured, this could be a proxy's - * IP address. - * @param logger The service logger to use. - */ - protected ConnectionHandler(final String connectionId, final String hostname, final ClientLogger logger) { + public ConnectionHandler(final String connectionId, final String hostname, String product, String clientVersion) { super(connectionId, hostname); add(new Handshaker()); - this.logger = logger; this.connectionProperties = new HashMap<>(); - this.connectionProperties.put(PRODUCT.toString(), ClientConstants.PRODUCT_NAME); - this.connectionProperties.put(VERSION.toString(), ClientConstants.CURRENT_JAVA_CLIENT_VERSION); + this.connectionProperties.put(PRODUCT.toString(), product); + this.connectionProperties.put(VERSION.toString(), clientVersion); this.connectionProperties.put(PLATFORM.toString(), ClientConstants.PLATFORM_INFO); this.connectionProperties.put(FRAMEWORK.toString(), ClientConstants.FRAMEWORK_INFO); + String userAgent = String.format(ClientConstants.USER_AGENT_TEMPLATE, product, clientVersion); - final String userAgent = ClientConstants.USER_AGENT.length() <= MAX_USER_AGENT_LENGTH - ? ClientConstants.USER_AGENT - : ClientConstants.USER_AGENT.substring(0, MAX_USER_AGENT_LENGTH); + userAgent = userAgent.length() <= MAX_USER_AGENT_LENGTH + ? userAgent + : userAgent.substring(0, MAX_USER_AGENT_LENGTH); this.connectionProperties.put(USER_AGENT.toString(), userAgent); } diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsConnectionHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsConnectionHandler.java index a2bbef6b297ac..965d378628911 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsConnectionHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsConnectionHandler.java @@ -20,15 +20,19 @@ public class WebSocketsConnectionHandler extends ConnectionHandler { private static final String SOCKET_PATH = "/$servicebus/websocket"; private static final String PROTOCOL = "AMQPWSB10"; + private final ClientLogger logger = new ClientLogger(WebSocketsConnectionHandler.class); /** * Creates a handler that handles proton-j's connection events using web sockets. * * @param connectionId Identifier for this connection. * @param hostname Hostname to use for socket creation. + * @param product The name of the product this connection handler is created for. + * @param clientVersion The version of the client library creating the connection handler. */ - public WebSocketsConnectionHandler(final String connectionId, final String hostname) { - super(connectionId, hostname, new ClientLogger(WebSocketsConnectionHandler.class)); + public WebSocketsConnectionHandler(final String connectionId, final String hostname, final String product, + final String clientVersion) { + super(connectionId, hostname, product, clientVersion); } @Override diff --git a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandler.java b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandler.java index 40f37c390138d..f649e4413e1e4 100644 --- a/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandler.java +++ b/sdk/core/azure-core-amqp/src/main/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandler.java @@ -48,11 +48,14 @@ public class WebSocketsProxyConnectionHandler extends WebSocketsConnectionHandle * @param connectionId Identifier for this connection. * @param amqpHostname Hostname of the AMQP message broker. The hostname of the proxy is exposed in {@link * #getHostname()}. + * @param proxyOptions The options to use for proxy. + * @param product The name of the product this connection handler is created for. + * @param clientVersion The version of the client library creating the connection handler. * @throws NullPointerException if {@code amqpHostname} or {@code proxyConfiguration} is null. */ public WebSocketsProxyConnectionHandler(String connectionId, String amqpHostname, - ProxyOptions proxyOptions) { - super(connectionId, amqpHostname); + ProxyOptions proxyOptions, String product, String clientVersion) { + super(connectionId, amqpHostname, product, clientVersion); this.amqpHostname = Objects.requireNonNull(amqpHostname, "'amqpHostname' cannot be null."); this.proxyOptions = Objects.requireNonNull(proxyOptions, "'proxyConfiguration' cannot be null."); this.remoteHost = amqpHostname + ":" + HTTPS_PORT; diff --git a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ActiveClientTokenManagerTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ActiveClientTokenManagerTest.java index 024d10714b9e0..45657132b9a9c 100644 --- a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ActiveClientTokenManagerTest.java +++ b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ActiveClientTokenManagerTest.java @@ -10,6 +10,7 @@ import com.azure.core.amqp.exception.AmqpResponseCode; import com.azure.core.exception.AzureException; 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; @@ -25,7 +26,7 @@ import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.when; -public class ActiveClientTokenManagerTest { +class ActiveClientTokenManagerTest { private static final String AUDIENCE = "an-audience-test"; private static final String SCOPES = "scopes-test"; private static final Duration TIMEOUT = Duration.ofSeconds(4); @@ -34,12 +35,12 @@ public class ActiveClientTokenManagerTest { private ClaimsBasedSecurityNode cbsNode; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); } @AfterEach - public void teardown() { + void teardown() { Mockito.framework().clearInlineMocks(); cbsNode = null; } @@ -48,7 +49,7 @@ public void teardown() { * Verify that we can get successes and errors from CBS node. */ @Test - public void getAuthorizationResults() { + void getAuthorizationResults() { // Arrange final Mono cbsNodeMono = Mono.fromCallable(() -> cbsNode); when(cbsNode.authorize(any(), any())).thenReturn(getNextExpiration(3)); @@ -60,8 +61,9 @@ public void getAuthorizationResults() { .then(() -> tokenManager.authorize().block(TIMEOUT)) .expectNext(AmqpResponseCode.ACCEPTED) .expectNext(AmqpResponseCode.ACCEPTED) - .then(tokenManager::close) - .verifyComplete(); + .then(() -> tokenManager.close()) + .expectComplete() + .verify(); } /** @@ -70,7 +72,7 @@ public void getAuthorizationResults() { */ @SuppressWarnings("unchecked") @Test - public void getAuthorizationResultsSuccessFailure() { + void getAuthorizationResultsSuccessFailure() { // Arrange final Mono cbsNodeMono = Mono.fromCallable(() -> cbsNode); final IllegalArgumentException error = new IllegalArgumentException("Some error"); @@ -83,6 +85,7 @@ public void getAuthorizationResultsSuccessFailure() { StepVerifier.create(tokenManager.getAuthorizationResults()) .then(() -> tokenManager.authorize().block(TIMEOUT)) .expectNext(AmqpResponseCode.ACCEPTED) + .expectNext(AmqpResponseCode.ACCEPTED) .expectError(IllegalArgumentException.class) .verifyThenAssertThat() .hasNotDroppedElements() @@ -95,7 +98,7 @@ public void getAuthorizationResultsSuccessFailure() { * Verify that we cannot authorize with CBS node when it has already been disposed of. */ @Test - public void cannotAuthorizeDisposedInstance() { + void cannotAuthorizeDisposedInstance() { // Arrange final Mono cbsNodeMono = Mono.fromCallable(() -> cbsNode); when(cbsNode.authorize(any(), any())).thenReturn(getNextExpiration(2)); @@ -114,31 +117,64 @@ public void cannotAuthorizeDisposedInstance() { */ @SuppressWarnings("unchecked") @Test - public void getAuthorizationResultsRetriableError() { + void getAuthorizationResultsRetriableError() { // Arrange final Mono cbsNodeMono = Mono.fromCallable(() -> cbsNode); - final AmqpException error = new AmqpException(true, AmqpErrorCondition.TIMEOUT_ERROR, "Timed out", + final AmqpException error = new AmqpException(false, AmqpErrorCondition.ARGUMENT_ERROR, + "Non-retryable argument error", new AmqpErrorContext("Test-context-namespace")); - when(cbsNode.authorize(any(), any())).thenReturn(getNextExpiration(3), Mono.error(error), - getNextExpiration(5), getNextExpiration(10), - getNextExpiration(45)); + when(cbsNode.authorize(any(), any())).thenReturn(getNextExpiration(5), Mono.error(error), + getNextExpiration(5)); // Act & Assert try (ActiveClientTokenManager tokenManager = new ActiveClientTokenManager(cbsNodeMono, AUDIENCE, SCOPES)) { StepVerifier.create(tokenManager.getAuthorizationResults()) .then(() -> tokenManager.authorize().block(TIMEOUT)) - .expectError(AmqpException.class) - .verify(); - - StepVerifier.create(tokenManager.getAuthorizationResults()) .expectNext(AmqpResponseCode.ACCEPTED) - .expectNext(AmqpResponseCode.ACCEPTED) - .then(tokenManager::close) - .verifyComplete(); + .expectErrorSatisfies(exception -> { + Assertions.assertTrue(exception instanceof AmqpException); + + AmqpException amqpException = (AmqpException) exception; + Assertions.assertFalse(amqpException.isTransient()); + Assertions.assertEquals(error.getErrorCondition(), amqpException.getErrorCondition()); + }) + .verify(Duration.ofSeconds(30)); } } + + /** + * Verify that the ActiveClientTokenManager does not get more authorization tasks. + */ + @SuppressWarnings("unchecked") + @Test + void getAuthorizationResultsNonRetriableError() { + // Arrange + final Mono cbsNodeMono = Mono.fromCallable(() -> cbsNode); + final AmqpException error = new AmqpException(true, AmqpErrorCondition.TIMEOUT_ERROR, "Test CBS node error.", + new AmqpErrorContext("Test-context-namespace")); + + when(cbsNode.authorize(any(), any())).thenReturn(getNextExpiration(5), Mono.error(error), + getNextExpiration(5), getNextExpiration(10), + getNextExpiration(45)); + + // Act & Assert + final ActiveClientTokenManager tokenManager = new ActiveClientTokenManager(cbsNodeMono, AUDIENCE, SCOPES); + + StepVerifier.create(tokenManager.getAuthorizationResults()) + .then(() -> tokenManager.authorize().block(TIMEOUT)) + .expectNext(AmqpResponseCode.ACCEPTED) + .expectNext(AmqpResponseCode.ACCEPTED) + .then(() -> { + System.out.println("Closing"); + tokenManager.close(); + }) + .expectComplete() + .verify(Duration.ofSeconds(30)); + } + + private Mono getNextExpiration(long secondsToWait) { return Mono.fromCallable(() -> OffsetDateTime.now(ZoneOffset.UTC).plusSeconds(secondsToWait)); } diff --git a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/AzureTokenManagerProviderTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/AzureTokenManagerProviderTest.java index 1c59251da4dca..3a150a63c234e 100644 --- a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/AzureTokenManagerProviderTest.java +++ b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/AzureTokenManagerProviderTest.java @@ -26,34 +26,34 @@ import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.when; -public class AzureTokenManagerProviderTest { +class AzureTokenManagerProviderTest { private static final String HOST_NAME = "foobar.windows.net"; @Mock private ClaimsBasedSecurityNode cbsNode; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); } @AfterEach - public void teardown() { + void teardown() { Mockito.framework().clearInlineMocks(); } @Test - public void constructorNullType() { + void constructorNullType() { assertThrows(NullPointerException.class, () -> new AzureTokenManagerProvider(null, HOST_NAME, "something.")); } @Test - public void constructorNullHost() { + void constructorNullHost() { assertThrows(NullPointerException.class, () -> new AzureTokenManagerProvider(CbsAuthorizationType.JSON_WEB_TOKEN, null, "some-scope")); } @Test - public void constructorNullScope() { + void constructorNullScope() { assertThrows(NullPointerException.class, () -> new AzureTokenManagerProvider(CbsAuthorizationType.JSON_WEB_TOKEN, HOST_NAME, null)); } @@ -62,7 +62,7 @@ public void constructorNullScope() { */ @ParameterizedTest @EnumSource(CbsAuthorizationType.class) - public void getResourceString(CbsAuthorizationType authorizationType) { + void getResourceString(CbsAuthorizationType authorizationType) { // Arrange final String scope = "some-scope"; final AzureTokenManagerProvider provider = new AzureTokenManagerProvider(authorizationType, HOST_NAME, scope); @@ -90,7 +90,7 @@ public void getResourceString(CbsAuthorizationType authorizationType) { * is generated from it. */ @Test - public void getCorrectTokenManagerSasToken() { + void getCorrectTokenManagerSasToken() { // Arrange final String aadScope = "some-active-directory-scope"; final AzureTokenManagerProvider provider = new AzureTokenManagerProvider(CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, HOST_NAME, aadScope); @@ -115,7 +115,7 @@ public void getCorrectTokenManagerSasToken() { * Verifies that for JWT token credentials, the scope is the the one that we expect from Azure AAD scope. */ @Test - public void getCorrectTokenManagerJwt() { + void getCorrectTokenManagerJwt() { // Arrange final String aadScope = "some-active-directory-scope"; final AzureTokenManagerProvider provider = new AzureTokenManagerProvider(CbsAuthorizationType.JSON_WEB_TOKEN, HOST_NAME, aadScope); @@ -135,4 +135,28 @@ public void getCorrectTokenManagerJwt() { .expectComplete() .verify(Duration.ofSeconds(10)); } + + /** + * Verify that if the same tokenAudience and scopes are passed in, the same {@link TokenManager} instance is + * returned. + */ + @Test + void differentInstanceReturned() { + // Arrange + final String aadScope = "some-active-directory-scope"; + final AzureTokenManagerProvider provider = new AzureTokenManagerProvider(CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, HOST_NAME, aadScope); + final String entityPath = "event-hub-test-2/partition/2"; + final String entityPath2 = "event-hub-test-2/partition/2"; + final AccessToken token = new AccessToken("a-new-access-token", OffsetDateTime.now().plusMinutes(10)); + final String tokenAudience = String.format(Locale.US, TOKEN_AUDIENCE_FORMAT, HOST_NAME, entityPath); + + when(cbsNode.authorize(argThat(audience -> audience.equals(tokenAudience)), argThat(scope -> scope.equals(tokenAudience)))) + .thenReturn(Mono.just(token.getExpiresAt())); + + // Act + final TokenManager tokenManager = provider.getTokenManager(Mono.just(cbsNode), entityPath); + final TokenManager tokenManager2 = provider.getTokenManager(Mono.just(cbsNode), entityPath2); + + Assertions.assertNotSame(tokenManager, tokenManager2); + } } diff --git a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/MockReactorHandlerProvider.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/MockReactorHandlerProvider.java index 5bf0eb3e6b486..a496c3603b301 100644 --- a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/MockReactorHandlerProvider.java +++ b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/MockReactorHandlerProvider.java @@ -33,8 +33,9 @@ public SessionHandler createSessionHandler(String connectionId, String hostname, } @Override - public ConnectionHandler createConnectionHandler(String connectionId, String hostname, AmqpTransportType transportType, - ProxyOptions configuration) { + public ConnectionHandler createConnectionHandler(String connectionId, String hostname, + AmqpTransportType transportType, ProxyOptions configuration, String product, String clientVersion) { + return connectionHandler; } diff --git a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorConnectionTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorConnectionTest.java index 318ea204fbe1d..c7920087df3dc 100644 --- a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorConnectionTest.java +++ b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorConnectionTest.java @@ -53,6 +53,8 @@ public class ReactorConnectionTest { private static final ConnectionStringProperties CREDENTIAL_INFO = new ConnectionStringProperties("Endpoint=sb://test-event-hub.servicebus.windows.net/;SharedAccessKeyName=dummySharedKeyName;SharedAccessKey=dummySharedKeyValue;EntityPath=eventhub1;"); private static final String HOSTNAME = CREDENTIAL_INFO.getEndpoint().getHost(); private static final Scheduler SCHEDULER = Schedulers.elastic(); + private static final String PRODUCT = "test"; + private static final String CLIENT_VERSION = "1.0.0-test"; private ReactorConnection connection; private SessionHandler sessionHandler; @@ -83,7 +85,7 @@ public void setup() throws IOException { when(reactor.selectable()).thenReturn(selectable); - connectionHandler = new ConnectionHandler(CONNECTION_ID, HOSTNAME); + connectionHandler = new ConnectionHandler(CONNECTION_ID, HOSTNAME, PRODUCT, CLIENT_VERSION); final ReactorDispatcher reactorDispatcher = new ReactorDispatcher(reactor); when(reactorProvider.getReactor()).thenReturn(reactor); @@ -99,7 +101,7 @@ public void setup() throws IOException { CREDENTIAL_INFO.getEntityPath(), tokenProvider, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP, retryOptions, ProxyOptions.SYSTEM_DEFAULTS, SCHEDULER); connection = new ReactorConnection(CONNECTION_ID, connectionOptions, reactorProvider, reactorHandlerProvider, - tokenManager, messageSerializer); + tokenManager, messageSerializer, PRODUCT, CLIENT_VERSION); } @AfterEach @@ -274,7 +276,7 @@ public void createCBSNode() { @Test public void createCBSNodeTimeoutException() { // Arrange - final ConnectionHandler handler = new ConnectionHandler(CONNECTION_ID, HOSTNAME); + final ConnectionHandler handler = new ConnectionHandler(CONNECTION_ID, HOSTNAME, PRODUCT, CLIENT_VERSION); final ReactorHandlerProvider provider = new MockReactorHandlerProvider(reactorProvider, handler, sessionHandler, null, null); @@ -290,7 +292,7 @@ public void createCBSNodeTimeoutException() { // Act and Assert try (ReactorConnection connectionBad = new ReactorConnection(CONNECTION_ID, parameters, reactorProvider, - provider, tokenManager, messageSerializer)) { + provider, tokenManager, messageSerializer, PRODUCT, CLIENT_VERSION)) { StepVerifier.create(connectionBad.getClaimsBasedSecurityNode()) .verifyError(TimeoutException.class); } diff --git a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorHandlerProviderTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorHandlerProviderTest.java index 71ec9f417833a..d02798a0e3e61 100644 --- a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorHandlerProviderTest.java +++ b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/ReactorHandlerProviderTest.java @@ -42,6 +42,8 @@ public class ReactorHandlerProviderTest { private static final Proxy PROXY = new Proxy(Proxy.Type.HTTP, PROXY_ADDRESS); private static final String USERNAME = "test-user"; private static final String PASSWORD = "test-password"; + private static final String PRODUCT = "test"; + private static final String CLIENT_VERSION = "1.0.0-test"; @Mock private Reactor reactor; @@ -84,7 +86,8 @@ public void teardown() { @Test public void getsConnectionHandlerAMQP() { // Act - final ConnectionHandler handler = provider.createConnectionHandler(CONNECTION_ID, HOSTNAME, AmqpTransportType.AMQP, null); + final ConnectionHandler handler = provider.createConnectionHandler(CONNECTION_ID, HOSTNAME, + AmqpTransportType.AMQP, null, PRODUCT, CLIENT_VERSION); // Assert Assertions.assertNotNull(handler); @@ -99,7 +102,7 @@ public void getsConnectionHandlerAMQP() { public void getsConnectionHandlerWebSockets(ProxyOptions configuration) { // Act final ConnectionHandler handler = provider.createConnectionHandler(CONNECTION_ID, HOSTNAME, - AmqpTransportType.AMQP_WEB_SOCKETS, configuration); + AmqpTransportType.AMQP_WEB_SOCKETS, configuration, PRODUCT, CLIENT_VERSION); // Assert Assertions.assertNotNull(handler); @@ -120,7 +123,7 @@ public void getsConnectionHandlerProxy() { // Act final ConnectionHandler handler = provider.createConnectionHandler(CONNECTION_ID, hostname, - AmqpTransportType.AMQP_WEB_SOCKETS, configuration); + AmqpTransportType.AMQP_WEB_SOCKETS, configuration, PRODUCT, CLIENT_VERSION); // Assert Assertions.assertNotNull(handler); @@ -144,7 +147,7 @@ public void noProxySelected(ProxyOptions configuration) { // Act final ConnectionHandler handler = provider.createConnectionHandler(CONNECTION_ID, hostname, - AmqpTransportType.AMQP_WEB_SOCKETS, configuration); + AmqpTransportType.AMQP_WEB_SOCKETS, configuration, PRODUCT, CLIENT_VERSION); // Act and Assert Assertions.assertEquals(PROXY_ADDRESS.getHostName(), handler.getHostname()); diff --git a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/ConnectionHandlerTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/ConnectionHandlerTest.java index 8313917799ef5..a23b94a85488f 100644 --- a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/ConnectionHandlerTest.java +++ b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/ConnectionHandlerTest.java @@ -26,9 +26,7 @@ import static com.azure.core.amqp.implementation.handler.ConnectionHandler.FRAMEWORK; import static com.azure.core.amqp.implementation.handler.ConnectionHandler.MAX_FRAME_SIZE; import static com.azure.core.amqp.implementation.handler.ConnectionHandler.PLATFORM; -import static com.azure.core.amqp.implementation.handler.ConnectionHandler.PRODUCT; import static com.azure.core.amqp.implementation.handler.ConnectionHandler.USER_AGENT; -import static com.azure.core.amqp.implementation.handler.ConnectionHandler.VERSION; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.times; @@ -39,6 +37,8 @@ public class ConnectionHandlerTest { private static final String CONNECTION_ID = "some-random-id"; private static final String HOSTNAME = "hostname-random"; private ConnectionHandler handler; + private static final String PRODUCT = "test"; + private static final String CLIENT_VERSION = "1.0.0-test"; @Captor private ArgumentCaptor> argumentCaptor; @@ -46,7 +46,7 @@ public class ConnectionHandlerTest { @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - handler = new ConnectionHandler(CONNECTION_ID, HOSTNAME); + handler = new ConnectionHandler(CONNECTION_ID, HOSTNAME, PRODUCT, CLIENT_VERSION); } @AfterEach @@ -59,8 +59,6 @@ public void teardown() { public void createHandler() { // Arrange final Map expected = new HashMap<>(); - expected.put(PRODUCT.toString(), ClientConstants.PRODUCT_NAME); - expected.put(VERSION.toString(), ClientConstants.CURRENT_JAVA_CLIENT_VERSION); expected.put(PLATFORM.toString(), ClientConstants.PLATFORM_INFO); expected.put(FRAMEWORK.toString(), ClientConstants.FRAMEWORK_INFO); diff --git a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/WebSocketsConnectionHandlerTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/WebSocketsConnectionHandlerTest.java index 519b5cb57a19d..e53151d18a1b3 100644 --- a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/WebSocketsConnectionHandlerTest.java +++ b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/WebSocketsConnectionHandlerTest.java @@ -24,8 +24,6 @@ import static com.azure.core.amqp.implementation.handler.ConnectionHandler.FRAMEWORK; import static com.azure.core.amqp.implementation.handler.ConnectionHandler.PLATFORM; -import static com.azure.core.amqp.implementation.handler.ConnectionHandler.PRODUCT; -import static com.azure.core.amqp.implementation.handler.ConnectionHandler.VERSION; import static com.azure.core.amqp.implementation.handler.WebSocketsConnectionHandler.HTTPS_PORT; import static com.azure.core.amqp.implementation.handler.WebSocketsConnectionHandler.MAX_FRAME_SIZE; import static org.mockito.ArgumentMatchers.any; @@ -39,13 +37,16 @@ public class WebSocketsConnectionHandlerTest { private static final String HOSTNAME = "hostname-random"; private WebSocketsConnectionHandler handler; + private static final String PRODUCT = "test"; + private static final String CLIENT_VERSION = "1.0.0-test"; + @Captor ArgumentCaptor> argumentCaptor; @BeforeEach public void setup() { MockitoAnnotations.initMocks(this); - handler = new WebSocketsConnectionHandler(CONNECTION_ID, HOSTNAME); + handler = new WebSocketsConnectionHandler(CONNECTION_ID, HOSTNAME, PRODUCT, CLIENT_VERSION); } @AfterEach @@ -58,8 +59,6 @@ public void teardown() { public void createHandler() { // Arrange final Map expected = new HashMap<>(); - expected.put(PRODUCT.toString(), ClientConstants.PRODUCT_NAME); - expected.put(VERSION.toString(), ClientConstants.CURRENT_JAVA_CLIENT_VERSION); expected.put(PLATFORM.toString(), ClientConstants.PLATFORM_INFO); expected.put(FRAMEWORK.toString(), ClientConstants.FRAMEWORK_INFO); diff --git a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandlerTest.java b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandlerTest.java index 6544f9a3aa730..23a4fd102b858 100644 --- a/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandlerTest.java +++ b/sdk/core/azure-core-amqp/src/test/java/com/azure/core/amqp/implementation/handler/WebSocketsProxyConnectionHandlerTest.java @@ -34,6 +34,8 @@ public class WebSocketsProxyConnectionHandlerTest { private static final String PASSWORD = "test-password"; private static final ProxyOptions PROXY_CONFIGURATION = new ProxyOptions(ProxyAuthenticationType.DIGEST, PROXY, USERNAME, PASSWORD); + private static final String PRODUCT = "test"; + private static final String CLIENT_VERSION = "1.0.0-test"; private ProxySelector originalProxySelector; private ProxySelector proxySelector; @@ -56,12 +58,14 @@ public void teardown() { @Test public void nullProxyConfiguration() { - assertThrows(NullPointerException.class, () -> new WebSocketsProxyConnectionHandler(CONNECTION_ID, HOSTNAME, null)); + assertThrows(NullPointerException.class, () -> new WebSocketsProxyConnectionHandler(CONNECTION_ID, HOSTNAME, + null, PRODUCT, CLIENT_VERSION)); } @Test public void nullHostname() { - assertThrows(NullPointerException.class, () -> new WebSocketsProxyConnectionHandler(CONNECTION_ID, null, PROXY_CONFIGURATION)); + assertThrows(NullPointerException.class, () -> new WebSocketsProxyConnectionHandler(CONNECTION_ID, null, + PROXY_CONFIGURATION, PRODUCT, CLIENT_VERSION)); } /** @@ -74,7 +78,7 @@ public void noProxySelected() { .thenReturn(Collections.singletonList(PROXY)); final WebSocketsProxyConnectionHandler handler = new WebSocketsProxyConnectionHandler(CONNECTION_ID, HOSTNAME, - PROXY_CONFIGURATION); + PROXY_CONFIGURATION, PRODUCT, CLIENT_VERSION); // Act and Assert Assertions.assertEquals(PROXY_ADDRESS.getHostName(), handler.getHostname()); @@ -91,7 +95,7 @@ public void systemProxyConfigurationSelected() { .thenReturn(Collections.singletonList(PROXY)); final WebSocketsProxyConnectionHandler handler = new WebSocketsProxyConnectionHandler(CONNECTION_ID, HOSTNAME, - ProxyOptions.SYSTEM_DEFAULTS); + ProxyOptions.SYSTEM_DEFAULTS, PRODUCT, CLIENT_VERSION); // Act and Assert Assertions.assertEquals(PROXY_ADDRESS.getHostName(), handler.getHostname()); @@ -114,7 +118,8 @@ public void proxyConfigurationSelected() { when(proxySelector.select(any())).thenReturn(Collections.singletonList(PROXY)); - final WebSocketsProxyConnectionHandler handler = new WebSocketsProxyConnectionHandler(CONNECTION_ID, host, configuration); + final WebSocketsProxyConnectionHandler handler = new WebSocketsProxyConnectionHandler(CONNECTION_ID, host, + configuration, PRODUCT, CLIENT_VERSION); // Act and Assert Assertions.assertEquals(address.getHostName(), handler.getHostname()); diff --git a/sdk/core/azure-core-http-netty/CHANGELOG.md b/sdk/core/azure-core-http-netty/CHANGELOG.md new file mode 100644 index 0000000000000..7113a024ad229 --- /dev/null +++ b/sdk/core/azure-core-http-netty/CHANGELOG.md @@ -0,0 +1,14 @@ +# Release History + +## 1.2.0 (2020-01-07) +- Upgrade netty dependencies to latest version + +## Version 1.1.0 (2019-11-26) +- Switch to JUnit version 5. + +## Version 1.0.0 (2019-10-29) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-core-http-netty_1.0.0/sdk/core/azure-core-http-netty/README.md) +and +[samples](https://github.com/Azure/azure-sdk-for-java/tree/azure-core-http-netty_1.0.0/sdk/core/azure-core-http-netty/src/samples/java/com/azure/core/http/netty) + diff --git a/sdk/core/azure-core-http-netty/README.md b/sdk/core/azure-core-http-netty/README.md index 871a6e279639c..ab730e281d3ef 100644 --- a/sdk/core/azure-core-http-netty/README.md +++ b/sdk/core/azure-core-http-netty/README.md @@ -15,7 +15,7 @@ Azure Core Netty HTTP client is a plugin for the azure-core HTTP client API. com.azure azure-core-http-netty - 1.0.0 + 1.2.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-http-netty/pom.xml b/sdk/core/azure-core-http-netty/pom.xml index 8e7045a0e0e13..09dd67eb2b661 100644 --- a/sdk/core/azure-core-http-netty/pom.xml +++ b/sdk/core/azure-core-http-netty/pom.xml @@ -15,7 +15,7 @@ com.azure azure-core-http-netty jar - 1.2.0-beta.1 + 1.3.0-beta.1 Microsoft Azure Netty HTTP Client Library This package contains the Netty HTTP client plugin for azure-core. @@ -58,7 +58,7 @@ com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 @@ -109,14 +109,14 @@ com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 test-jar test com.azure azure-core-test - 1.1.0-beta.2 + 1.2.0-beta.1 test diff --git a/sdk/core/azure-core-http-okhttp/CHANGELOG.md b/sdk/core/azure-core-http-okhttp/CHANGELOG.md new file mode 100644 index 0000000000000..fde4a1cfa7126 --- /dev/null +++ b/sdk/core/azure-core-http-okhttp/CHANGELOG.md @@ -0,0 +1,12 @@ +# Release History + +## 1.1.0 (2020-01-07) +- Updated version of dependent libraries. + +## Version 1.0.0 (2019-10-29) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-core_1.0.0/sdk/core/azure-core-http-okhttp/README.md) +and +[samples](https://github.com/Azure/azure-sdk-for-java/tree/azure-core_1.0.0/sdk/core/azure-core-http-okhttp/src/samples/java/com/azure/core/http/okhttp) + +- Initial release. Please see the README and wiki for information on the new design. diff --git a/sdk/core/azure-core-http-okhttp/README.md b/sdk/core/azure-core-http-okhttp/README.md index 7804f0c333e61..87f0ec97e9fe0 100644 --- a/sdk/core/azure-core-http-okhttp/README.md +++ b/sdk/core/azure-core-http-okhttp/README.md @@ -15,7 +15,7 @@ Azure Core OkHttp HTTP client is a plugin for the azure-core HTTP client API. com.azure azure-core-http-okhttp - 1.0.0 + 1.1.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-http-okhttp/pom.xml b/sdk/core/azure-core-http-okhttp/pom.xml index b0d5457ffbf86..50b0e3bc187ed 100644 --- a/sdk/core/azure-core-http-okhttp/pom.xml +++ b/sdk/core/azure-core-http-okhttp/pom.xml @@ -15,7 +15,7 @@ com.azure azure-core-http-okhttp jar - 1.1.0-beta.1 + 1.2.0-beta.1 Microsoft Azure OkHttp HTTP Client Library This package contains the OkHttp HTTP client plugin for azure-core. @@ -59,7 +59,7 @@ com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 @@ -72,14 +72,14 @@ com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 test-jar test com.azure azure-core-test - 1.1.0-beta.2 + 1.2.0-beta.1 test diff --git a/sdk/core/azure-core-management/CHANGELOG.md b/sdk/core/azure-core-management/CHANGELOG.md new file mode 100644 index 0000000000000..2bd5f4012be3a --- /dev/null +++ b/sdk/core/azure-core-management/CHANGELOG.md @@ -0,0 +1,8 @@ +# Release History + +## 1.0.0-preview.4 (2019-09-09) + +## Version 1.0.0-preview.3 (2019-08-05) + +## Version 1.0.0-preview.1 (2019-06-28) +- Initial release. This package contains Microsoft Azure SDK for Template. diff --git a/sdk/core/azure-core-management/pom.xml b/sdk/core/azure-core-management/pom.xml index e90789f813503..233036eeb3c43 100644 --- a/sdk/core/azure-core-management/pom.xml +++ b/sdk/core/azure-core-management/pom.xml @@ -57,7 +57,7 @@ com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 @@ -76,13 +76,13 @@ com.azure azure-core-test - 1.1.0-beta.2 + 1.2.0-beta.1 test com.azure azure-core-http-netty - 1.2.0-beta.1 + 1.3.0-beta.1 test diff --git a/sdk/core/azure-core-test/CHANGELOG.md b/sdk/core/azure-core-test/CHANGELOG.md new file mode 100644 index 0000000000000..efda3f8736261 --- /dev/null +++ b/sdk/core/azure-core-test/CHANGELOG.md @@ -0,0 +1,18 @@ +# Release History + +## 1.1.0 (2020-01-07) + +## 1.1.0-beta.2 (2019-12-18) +- Quick release to have client library depends on the right version of azure-core and azure-core-test changes. + +## Version 1.1.0-beta.1 (2019-12-17) +- Added log message if playback json file is missing. +- Fixed bug which record failed for newly added tests. +- Switch to JUnit version 5. +- Allowed to record body when content type is not set. + +## Version 1.0.0 (2019-10-29) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-core-test_1.0.0/sdk/core/azure-core-test/README.md) + +- Initial release. Please see the README and wiki for information on the new design. diff --git a/sdk/core/azure-core-test/README.md b/sdk/core/azure-core-test/README.md index 37a7a50251f66..e1152a091f1dd 100644 --- a/sdk/core/azure-core-test/README.md +++ b/sdk/core/azure-core-test/README.md @@ -18,7 +18,7 @@ To use this package, add the following to your _pom.xml_. com.azure azure-core-test - 1.0.0 + 1.1.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-test/pom.xml b/sdk/core/azure-core-test/pom.xml index 760e2f9e1752e..e000a51030872 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.1.0-beta.2 + 1.2.0-beta.1 Microsoft Azure Java Core Test Library This package contains core test types for Azure Java clients. @@ -38,7 +38,7 @@ com.azure azure-core - 1.1.0 + 1.2.0 diff --git a/sdk/core/azure-core-tracing-opencensus/CHANGELOG.md b/sdk/core/azure-core-tracing-opencensus/CHANGELOG.md index 2af5dfe9deb26..e94dda12e95c3 100644 --- a/sdk/core/azure-core-tracing-opencensus/CHANGELOG.md +++ b/sdk/core/azure-core-tracing-opencensus/CHANGELOG.md @@ -1,6 +1,8 @@ # Release History -## 1.0.0-beta.6 (Unreleased) +## 1.0.0-beta.6 (2020-01-07) +- Shorten tracing span names +- Add eventhub properties to processing spans ## 1.0.0-beta.5 (2019-11-26) For details on the Azure SDK for Java (December 2019 Preview) release refer to the [release announcement](https://aka.ms/azure-sdk-preview6-java). diff --git a/sdk/core/azure-core-tracing-opencensus/README.md b/sdk/core/azure-core-tracing-opencensus/README.md index 00a7c834c67e0..f0f05a1791231 100644 --- a/sdk/core/azure-core-tracing-opencensus/README.md +++ b/sdk/core/azure-core-tracing-opencensus/README.md @@ -19,7 +19,7 @@ documentation][api_documentation] | [Samples][samples] com.azure azure-core-tracing-opencensus - 1.0.0-beta.5 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opencensus/pom.xml b/sdk/core/azure-core-tracing-opencensus/pom.xml index da4ee56f66477..839d28a294f73 100644 --- a/sdk/core/azure-core-tracing-opencensus/pom.xml +++ b/sdk/core/azure-core-tracing-opencensus/pom.xml @@ -12,7 +12,7 @@ com.azure azure-core-tracing-opencensus - 1.0.0-beta.6 + 1.0.0-beta.7 Microsoft Azure OpenCensus tracing plugin This package contains the OpenCensus tracing plugin for Azure client libraries. @@ -35,7 +35,7 @@ com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 io.opencensus diff --git a/sdk/core/azure-core-tracing-opencensus/src/samples/AsyncListKeyVaultSecrets.md b/sdk/core/azure-core-tracing-opencensus/src/samples/AsyncListKeyVaultSecrets.md index 1e29612b229dd..8e8d5914007c7 100644 --- a/sdk/core/azure-core-tracing-opencensus/src/samples/AsyncListKeyVaultSecrets.md +++ b/sdk/core/azure-core-tracing-opencensus/src/samples/AsyncListKeyVaultSecrets.md @@ -12,7 +12,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-security-keyvault-secrets - 4.0.1 + 4.1.0 ``` [//]: # ({x-version-update-end}) @@ -22,7 +22,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-core-tracing-opencensus - 1.0.0-beta.5 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opencensus/src/samples/AsyncQueueClientEnqueueMessages.md b/sdk/core/azure-core-tracing-opencensus/src/samples/AsyncQueueClientEnqueueMessages.md index 27e2066b6f39b..cd8f6493ad9de 100644 --- a/sdk/core/azure-core-tracing-opencensus/src/samples/AsyncQueueClientEnqueueMessages.md +++ b/sdk/core/azure-core-tracing-opencensus/src/samples/AsyncQueueClientEnqueueMessages.md @@ -14,7 +14,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-storage-queue - 12.1.0 + 12.2.0 ``` [//]: # ({x-version-update-end}) @@ -24,7 +24,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-core-tracing-opencensus - 1.0.0-beta.5 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opencensus/src/samples/ListeKeyVaultSecrets.md b/sdk/core/azure-core-tracing-opencensus/src/samples/ListeKeyVaultSecrets.md index 4ed8864983f82..8a22ff882e086 100644 --- a/sdk/core/azure-core-tracing-opencensus/src/samples/ListeKeyVaultSecrets.md +++ b/sdk/core/azure-core-tracing-opencensus/src/samples/ListeKeyVaultSecrets.md @@ -13,7 +13,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-security-keyvault-secrets - 4.0.1 + 4.1.0 ``` [//]: # ({x-version-update-end}) @@ -23,7 +23,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-core-tracing-opencensus - 1.0.0-beta.5 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opencensus/src/samples/PublishEvents.md b/sdk/core/azure-core-tracing-opencensus/src/samples/PublishEvents.md index 29674153f9b8b..0aa1922558a4e 100644 --- a/sdk/core/azure-core-tracing-opencensus/src/samples/PublishEvents.md +++ b/sdk/core/azure-core-tracing-opencensus/src/samples/PublishEvents.md @@ -14,7 +14,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-messaging-eventhubs - 5.0.0-beta.6 + 5.0.1 ``` [//]: # ({x-version-update-end}) @@ -24,7 +24,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-core-tracing-opencensus - 1.0.0-beta.5 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opencensus/src/samples/QueueClientEnqueueMessages.md b/sdk/core/azure-core-tracing-opencensus/src/samples/QueueClientEnqueueMessages.md index 8ce90a2ff7907..accb762359e99 100644 --- a/sdk/core/azure-core-tracing-opencensus/src/samples/QueueClientEnqueueMessages.md +++ b/sdk/core/azure-core-tracing-opencensus/src/samples/QueueClientEnqueueMessages.md @@ -14,7 +14,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-storage-queue - 12.1.0 + 12.2.0 ``` [//]: # ({x-version-update-end}) @@ -24,7 +24,7 @@ Sample uses **[opencensus-impl][opencensus_impl]** as implementation package and com.azure azure-core-tracing-opencensus - 1.0.0-beta.5 + 1.0.0-beta.6 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md b/sdk/core/azure-core-tracing-opentelemetry/CHANGELOG.md index 926998025d893..2d03ed4fd3afb 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.2 (2020-01-03) +## 1.0.0-beta.2 (2020-01-07) - Add `EventHubs.*` properties to attributes of processing spans. - Remove `Azure` prefix from convenience layer span names. - Add links for batch send operation in Event Hubs client library. diff --git a/sdk/core/azure-core-tracing-opentelemetry/README.md b/sdk/core/azure-core-tracing-opentelemetry/README.md index 772a8b26ac5af..307e72118cf05 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/README.md +++ b/sdk/core/azure-core-tracing-opentelemetry/README.md @@ -19,7 +19,7 @@ documentation][api_documentation] | [Samples][samples] com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opentelemetry/pom.xml b/sdk/core/azure-core-tracing-opentelemetry/pom.xml index 4742881c7877d..ff6c0adefb084 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.2 + 1.0.0-beta.3 Microsoft Azure OpenTelemetry tracing plugin This package contains the OpenTelemetry tracing plugin for Azure client libraries. @@ -40,7 +40,7 @@ com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 diff --git a/sdk/core/azure-core-tracing-opentelemetry/src/samples/AsyncListKeyVaultSecretsSample.md b/sdk/core/azure-core-tracing-opentelemetry/src/samples/AsyncListKeyVaultSecretsSample.md index 8363154334c7f..88eadefdf4bda 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/src/samples/AsyncListKeyVaultSecretsSample.md +++ b/sdk/core/azure-core-tracing-opentelemetry/src/samples/AsyncListKeyVaultSecretsSample.md @@ -23,7 +23,7 @@ Sample uses **[opentelemetry-sdk][opentelemetry_sdk]** as implementation package com.azure azure-security-keyvault-secrets - 4.0.1 + 4.1.0 ``` [//]: # ({x-version-update-end}) @@ -32,7 +32,7 @@ Sample uses **[opentelemetry-sdk][opentelemetry_sdk]** as implementation package com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opentelemetry/src/samples/CreateConfigurationSettingTracingSample.md b/sdk/core/azure-core-tracing-opentelemetry/src/samples/CreateConfigurationSettingTracingSample.md index 76df142d273df..5c87cbe731501 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/src/samples/CreateConfigurationSettingTracingSample.md +++ b/sdk/core/azure-core-tracing-opentelemetry/src/samples/CreateConfigurationSettingTracingSample.md @@ -23,7 +23,7 @@ Sample uses **[opentelemetry-sdk][opentelemetry_sdk]** as implementation package com.azure azure-data-appconfiguration - 1.0.0-beta.7 + 1.0.1 ``` [//]: # ({x-version-update-end}) @@ -32,7 +32,7 @@ Sample uses **[opentelemetry-sdk][opentelemetry_sdk]** as implementation package com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opentelemetry/src/samples/ListKeyVaultSecretsTracingSample.md b/sdk/core/azure-core-tracing-opentelemetry/src/samples/ListKeyVaultSecretsTracingSample.md index 289faf51bc67e..760d9304e526c 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/src/samples/ListKeyVaultSecretsTracingSample.md +++ b/sdk/core/azure-core-tracing-opentelemetry/src/samples/ListKeyVaultSecretsTracingSample.md @@ -23,7 +23,7 @@ Sample uses **[opentelemetry-sdk][opentelemetry_sdk]** as implementation package com.azure azure-security-keyvault-secrets - 4.0.1 + 4.1.0 ``` [//]: # ({x-version-update-end}) @@ -32,7 +32,7 @@ Sample uses **[opentelemetry-sdk][opentelemetry_sdk]** as implementation package com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core-tracing-opentelemetry/src/samples/PublishEventsTracingSample.md b/sdk/core/azure-core-tracing-opentelemetry/src/samples/PublishEventsTracingSample.md index 6256f61fba68e..e7243cc6b0687 100644 --- a/sdk/core/azure-core-tracing-opentelemetry/src/samples/PublishEventsTracingSample.md +++ b/sdk/core/azure-core-tracing-opentelemetry/src/samples/PublishEventsTracingSample.md @@ -23,7 +23,7 @@ Sample uses **[opentelemetry-sdk][opentelemetry_sdk]** for implementation and ** com.azure azure-messaging-eventhubs - 5.0.0-beta.6 + 5.0.1 ``` [//]: # ({x-version-update-end}) @@ -32,7 +32,7 @@ Sample uses **[opentelemetry-sdk][opentelemetry_sdk]** for implementation and ** com.azure azure-core-tracing-opentelemetry - 1.0.0-beta.1 + 1.0.0-beta.2 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core/CHANGELOG.md b/sdk/core/azure-core/CHANGELOG.md index f42e0e020f4b9..64686db0d1a51 100644 --- a/sdk/core/azure-core/CHANGELOG.md +++ b/sdk/core/azure-core/CHANGELOG.md @@ -1,6 +1,15 @@ # Release History -## 1.2.0-beta.1 (Unreleased) +## 1.2.0 (2020-01-07) +- Ignore null headers and allow full url paths +- Add missing HTTP request methods to HttpMethod enum +- Support custom header with AddHeaderPolicy +- Support custom header name in RequestIDPolicy +- Prevent HttpLoggingPolicy Consuming Body +- Hide secret info from log info +- Ensure HTTPS is used when authenticating with tokens +- Reduce Prefetch Limit for PagedIterable and IterableStream +- Add Iterable overload for IterableStream ## Version 1.1.0 (2019-11-26) - Added support for creating reactor-netty-http client from an existing client. diff --git a/sdk/core/azure-core/README.md b/sdk/core/azure-core/README.md index 9d3e946a097a7..9c022e439f994 100644 --- a/sdk/core/azure-core/README.md +++ b/sdk/core/azure-core/README.md @@ -15,7 +15,7 @@ Typically, you will not need to install or specifically depend on Azure Core, in com.azure azure-core - 1.0.0 + 1.2.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/core/azure-core/pom.xml b/sdk/core/azure-core/pom.xml index 0cae6624246b5..be89b5161daba 100644 --- a/sdk/core/azure-core/pom.xml +++ b/sdk/core/azure-core/pom.xml @@ -14,7 +14,7 @@ com.azure azure-core jar - 1.2.0-beta.1 + 1.3.0-beta.1 Microsoft Azure Java Core Library This package contains core types for Azure Java clients. diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java index 50f6a5f196ad5..9e0b153593ba1 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/http/policy/HttpLoggingPolicy.java @@ -10,11 +10,11 @@ import com.azure.core.http.HttpPipelineNextPolicy; import com.azure.core.http.HttpRequest; import com.azure.core.http.HttpResponse; -import com.azure.core.implementation.LogLevel; import com.azure.core.implementation.LoggingUtil; import com.azure.core.util.CoreUtils; import com.azure.core.util.UrlBuilder; import com.azure.core.util.logging.ClientLogger; +import com.azure.core.util.logging.LogLevel; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.SerializationFeature; import reactor.core.publisher.Mono; @@ -101,7 +101,8 @@ public Mono process(HttpPipelineCallContext context, HttpPipelineN * @return A Mono which will emit the string to log. */ private Mono logRequest(final ClientLogger logger, final HttpRequest request) { - int numericLogLevel = LoggingUtil.getEnvironmentLoggingLevel().toNumeric(); + int numericLogLevel = LoggingUtil.getEnvironmentLoggingLevel().getLogLevel(); + if (shouldLoggingBeSkipped(numericLogLevel)) { return Mono.empty(); } @@ -181,7 +182,7 @@ private Mono logRequest(final ClientLogger logger, final HttpRequest reque * @return A Mono containing the HTTP response. */ private Mono logResponse(final ClientLogger logger, final HttpResponse response, long startNs) { - int numericLogLevel = LoggingUtil.getEnvironmentLoggingLevel().toNumeric(); + int numericLogLevel = LoggingUtil.getEnvironmentLoggingLevel().getLogLevel(); if (shouldLoggingBeSkipped(numericLogLevel)) { return Mono.just(response); } @@ -260,7 +261,7 @@ private Mono logAndReturn(ClientLogger logger, StringBuilder logMessageBu * @return A flag indicating if logging should be skipped. */ private boolean shouldLoggingBeSkipped(int environmentLogLevel) { - return environmentLogLevel > LogLevel.INFORMATIONAL.toNumeric(); + return environmentLogLevel > LogLevel.INFORMATIONAL.getLogLevel(); } /* @@ -318,7 +319,7 @@ private String getAllowedQueryString(String queryString) { */ private void addHeadersToLogMessage(HttpHeaders headers, StringBuilder sb, int logLevel) { // Either headers shouldn't be logged or the logging level isn't set to VERBOSE, don't add headers. - if (!httpLogDetailLevel.shouldLogHeaders() || logLevel > LogLevel.VERBOSE.toNumeric()) { + if (!httpLogDetailLevel.shouldLogHeaders() || logLevel > LogLevel.VERBOSE.getLogLevel()) { return; } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/LogLevel.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/LogLevel.java deleted file mode 100644 index 56c83b5c59098..0000000000000 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/LogLevel.java +++ /dev/null @@ -1,49 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.core.implementation; - -/** - * Enum which represent logging levels used in Azure SDKs. - */ -public enum LogLevel { - /** - * Indicates that log level is at verbose level. - */ - VERBOSE(1), - - /** - * Indicates that log level is at information level. - */ - INFORMATIONAL(2), - - /** - * Indicates that log level is at warning level. - */ - WARNING(3), - - /** - * Indicates that log level is at error level. - */ - ERROR(4), - - /** - * Indicates that logging is disabled. - */ - DISABLED(5); - - private final int numericValue; - - LogLevel(int numericValue) { - this.numericValue = numericValue; - } - - /** - * Converts the log level into a numeric representation used for comparisons. - * - * @return The numeric representation of the log level. - */ - public int toNumeric() { - return numericValue; - } -} diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/LoggingUtil.java b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/LoggingUtil.java index bfff5d5316386..3f7eb257a99e7 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/implementation/LoggingUtil.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/implementation/LoggingUtil.java @@ -4,33 +4,24 @@ package com.azure.core.implementation; import com.azure.core.util.Configuration; -import com.azure.core.util.CoreUtils; - -import java.util.Arrays; -import java.util.Map; -import java.util.stream.Collectors; +import com.azure.core.util.logging.LogLevel; /** * This class contains utility methods useful for logging. */ public final class LoggingUtil { - private static final Map LOG_LEVEL_MAPPER = Arrays.stream(LogLevel.values()) - .collect(Collectors.toMap(LogLevel::toNumeric, logLevel -> logLevel)); - /** * Retrieve the environment logging level which is used to determine if and what we are allowed to log. * *

The value returned from this method should be used throughout a single logging event as it may change during * the logging operation, this will help prevent difficult to debug timing issues.

* - * @return Environment logging level if set, otherwise {@link LogLevel#DISABLED}. + * @return Environment logging level if set, otherwise {@link LogLevel#NOT_SET}. */ public static LogLevel getEnvironmentLoggingLevel() { String environmentLogLevel = Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_LOG_LEVEL); - return CoreUtils.isNullOrEmpty(environmentLogLevel) - ? LogLevel.DISABLED - : LOG_LEVEL_MAPPER.getOrDefault(Integer.parseInt(environmentLogLevel), LogLevel.DISABLED); + return LogLevel.fromString(environmentLogLevel); } // Private constructor diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java index 27868d089e66c..0938669d75a27 100644 --- a/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/ClientLogger.java @@ -3,7 +3,6 @@ package com.azure.core.util.logging; -import com.azure.core.implementation.LogLevel; import com.azure.core.util.Configuration; import com.azure.core.util.CoreUtils; import org.slf4j.Logger; @@ -173,6 +172,16 @@ private RuntimeException logException(RuntimeException runtimeException, LogLeve return runtimeException; } + /** + * Determines if the environment and logger support logging at the given log level. + * + * @param logLevel The {@link LogLevel} being validated as supported. + * @return Flag indicating if the environment and logger support logging at the given log level. + */ + public boolean canLogAtLevel(LogLevel logLevel) { + return canLogAtLevel(logLevel, getEnvironmentLoggingLevel()); + } + /* * Performs the logging. * @@ -198,7 +207,7 @@ private void performLogging(LogLevel logLevel, LogLevel environmentLogLevel, boo * Environment is logging at a level higher than verbose, strip out the throwable as it would log its * stack trace which is only expected when logging at a verbose level. */ - if (environmentLogLevel.toNumeric() > LogLevel.VERBOSE.toNumeric()) { + if (environmentLogLevel.getLogLevel() > LogLevel.VERBOSE.getLogLevel()) { args = removeThrowable(args); } } @@ -236,8 +245,13 @@ private void performLogging(LogLevel logLevel, LogLevel environmentLogLevel, boo * @return Flag indicating if the environment and logger are configured to support logging at the given log level. */ private boolean canLogAtLevel(LogLevel logLevel, LogLevel environmentLoggingLevel) { + // Do not log if logLevel is null is not set. + if (logLevel == null) { + return false; + } + // Attempting to log at a level not supported by the environment. - if (logLevel.toNumeric() < environmentLoggingLevel.toNumeric()) { + if (logLevel.getLogLevel() < environmentLoggingLevel.getLogLevel()) { return false; } diff --git a/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/LogLevel.java b/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/LogLevel.java new file mode 100644 index 0000000000000..83b603d17b1e8 --- /dev/null +++ b/sdk/core/azure-core/src/main/java/com/azure/core/util/logging/LogLevel.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.core.util.logging; + +import java.util.HashMap; +import java.util.Locale; + +/** + * Enum which represent logging levels used in Azure SDKs. + */ +public enum LogLevel { + /** + * 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"), + + /** + * Indicates that no log level is set. + */ + NOT_SET(5); + + private final int numericValue; + private final String[] allowedLogLevelVariables; + private static final HashMap LOG_LEVEL_STRING_MAPPER = new HashMap<>(); + + 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; + } + + /** + * Converts the log level into a numeric representation used for comparisons. + * + * @return The numeric representation of the log level. + */ + public int getLogLevel() { + return numericValue; + } + + /** + * 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.NOT_SET; + } + 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); + } +} diff --git a/sdk/core/azure-core/src/test/java/com/azure/core/util/logging/ClientLoggerTests.java b/sdk/core/azure-core/src/test/java/com/azure/core/util/logging/ClientLoggerTests.java index be652413517d7..f7794a5411683 100644 --- a/sdk/core/azure-core/src/test/java/com/azure/core/util/logging/ClientLoggerTests.java +++ b/sdk/core/azure-core/src/test/java/com/azure/core/util/logging/ClientLoggerTests.java @@ -9,13 +9,16 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.junit.jupiter.params.ParameterizedTest; +import org.junit.jupiter.params.provider.CsvSource; import org.junit.jupiter.params.provider.ValueSource; import java.io.ByteArrayOutputStream; import java.io.PrintStream; import java.nio.charset.StandardCharsets; +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; /** @@ -103,15 +106,19 @@ public void logAtUnsupportedLevel(int logLevel) { */ @ParameterizedTest(name = PARAMETERIZED_TEST_NAME_TEMPLATE) @ValueSource(ints = { 1, 2, 3, 4 }) - public void logWhenLoggingDisabled(int logLevel) { + public void logWhenLoggingInvalidNumeric(int logLevel) { String logMessage = "This is a test"; + setupLogLevel(5); + assertThrows(IllegalArgumentException.class, () -> + logMessage(new ClientLogger(ClientLoggerTests.class), logLevel, logMessage)); + } - String originalLogLevel = setupLogLevel(5); - logMessage(new ClientLogger(ClientLoggerTests.class), logLevel, logMessage); - setPropertyToOriginalOrClear(Configuration.PROPERTY_AZURE_LOG_LEVEL, originalLogLevel); - - String logValues = new String(logCaptureStream.toByteArray(), StandardCharsets.UTF_8); - assertFalse(logValues.contains(logMessage)); + /** + * Tests that logging when the environment log level is disabled nothing is logged. + */ + @Test + public void logWhenLoggingNotSet() { + assertEquals(LogLevel.NOT_SET, LogLevel.fromString(null)); } /** @@ -276,10 +283,24 @@ public void logExceptionAsErrorStackTrace() { assertTrue(logValues.contains(runtimeException.getStackTrace()[0].toString())); } + @ParameterizedTest(name = "{index} from logLevelToConfigure = {0}, logLevelToValidate = {1}, expected = {2}") + @CsvSource({"1, 1, true", "1, 2, true", "1, 3, true", "1, 4, true", "2, 1, false", "1, VERBOSE, true", "1, info, true", "1, warning, true", "1, error, true", "2, verbose, false"}) + public void canLogAtLevel(int logLevelToConfigure, String logLevelToValidate, boolean expected) { + setupLogLevel(logLevelToConfigure); + LogLevel logLevel = LogLevel.fromString(logLevelToValidate); + assertEquals(new ClientLogger(ClientLoggerTests.class).canLogAtLevel(logLevel), expected); + } + + @ParameterizedTest(name = PARAMETERIZED_TEST_NAME_TEMPLATE) + @ValueSource(strings = {"5", "invalid"}) + public void canLogAtLevelInvalid(String logLevelToValidate) { + setupLogLevel(2); + assertThrows(IllegalArgumentException.class, () -> LogLevel.fromString(logLevelToValidate)); + } + private String setupLogLevel(int logLevelToSet) { String originalLogLevel = Configuration.getGlobalConfiguration().get(Configuration.PROPERTY_AZURE_CLOUD); System.setProperty(Configuration.PROPERTY_AZURE_LOG_LEVEL, Integer.toString(logLevelToSet)); - return originalLogLevel; } diff --git a/sdk/cosmos/CODEOWNERS b/sdk/cosmos/CODEOWNERS index 26da20e9f2cf2..732eb0de8569a 100644 --- a/sdk/cosmos/CODEOWNERS +++ b/sdk/cosmos/CODEOWNERS @@ -7,4 +7,4 @@ # https://help.github.com/articles/about-codeowners/ # Default owner for repo -* @moderakh @christopheranderson @kushagraThapar +* @moderakh @kushagraThapar @David-Noble-at-work @kirankumarkolli diff --git a/sdk/cosmos/README.md b/sdk/cosmos/README.md index 0d4cc1006c543..3a5b1b1930cb6 100644 --- a/sdk/cosmos/README.md +++ b/sdk/cosmos/README.md @@ -92,7 +92,7 @@ For example, using maven, you can add the following dependency to your maven pom com.microsoft.azure azure-cosmos - 3.5.1-beta1 + 3.6.0-beta.2 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/cosmos/changelog/README.md b/sdk/cosmos/changelog/README.md index 97ddeccad8037..9040570dc8bfd 100644 --- a/sdk/cosmos/changelog/README.md +++ b/sdk/cosmos/changelog/README.md @@ -1,4 +1,44 @@ ## Changelog +### 3.6.0-beta.1 +- Added the ability to select default Direct TCP options + + In priority order we will take default Direct TCP options from: + + - The string value of system property `"azure.cosmos.directTcp.options"` + + Example: + ``` + -Dazure.cosmos.directTcp.defaultOptions={\"idleEndpointTimeout\":"PT1M10S",\"maxChannelsPerEndpoint\":10,\"maxRequestsPerChannel\":30} + ``` + - The contents of the file located by the system property "azure.cosmos.directTcp.defaultOptionsFile". + + Example: + ``` + -Dazure.cosmos.directTcp.defaultOptionsFile=/path/to/default/options/file + ``` + + - The contents of the resource file named `"azure.cosmos.directTcp.options.json"` + + Otherwise, if none of these values are set or an error occurs we create default options based on a set of hard-wired + values defined in the default private parameterless constructor for `RntbdTransportClient.Options` as we did before + this release. + +- Fixed Reactor Netty connection re-use issue: https://github.com/Azure/azure-sdk-for-java/issues/6973 + +### 3.5.0 +- Changefeed bug fixes (includes all the bug fixes released in 3.3.3) +- Disaster Recovery related bug fixes +- Exception when Cosmos DB HTTP response header is larger than 8192 bytes: https://github.com/Azure/azure-sdk-for-java/issues/6069 +- Vulnerability through dependency in the SDK: https://github.com/Azure/azure-sdk-for-java/issues/6433 +- CosmosSyncScripts null pointer exception in azure-cosmos: https://github.com/Azure/azure-sdk-for-java/issues/6281 +- Default consistency level parsing for Bounded Staleness and Consistent Prefix: https://github.com/Azure/azure-sdk-for-java/issues/6707 +- Collection cache improvements: https://github.com/Azure/azure-sdk-for-java/issues/6307 + +### 3.4.0 +- Added QueryPlan +- Added OffsetLimit support +- ChangeFeedProcessor; fixes and extra logging related to the creations of the lease documents. +- Port consistency policy bug fix (see Azure/azure-cosmosdb-java#196) ### 3.5.0 - Changefeed bug fixes (includes all the bug fixes released in 3.3.3) diff --git a/sdk/cosmos/microsoft-azure-cosmos-benchmark/pom.xml b/sdk/cosmos/microsoft-azure-cosmos-benchmark/pom.xml index 1b3f977beda62..6c03a5106eff5 100644 --- a/sdk/cosmos/microsoft-azure-cosmos-benchmark/pom.xml +++ b/sdk/cosmos/microsoft-azure-cosmos-benchmark/pom.xml @@ -8,12 +8,12 @@ Licensed under the MIT License. com.microsoft.azure azure-cosmos-parent - 3.5.1-beta1 + 3.5.0 com.microsoft.azure azure-cosmos-benchmark - 3.5.1-beta1 + 3.6.0-beta.2 Microsoft Azure SDK for SQL API of Azure Cosmos DB Service - Benchmarking tool This package contains Benchmarking tool for Microsoft Azure SDK for SQL API of Azure Cosmos DB Service https://github.com/Azure/azure-sdk-for-java @@ -33,7 +33,7 @@ Licensed under the MIT License. com.microsoft.azure azure-cosmos - 3.5.1-beta1 + 3.6.0-beta.2 diff --git a/sdk/cosmos/microsoft-azure-cosmos-examples/pom.xml b/sdk/cosmos/microsoft-azure-cosmos-examples/pom.xml index 890d3fd1157cd..6725d42a1bcda 100644 --- a/sdk/cosmos/microsoft-azure-cosmos-examples/pom.xml +++ b/sdk/cosmos/microsoft-azure-cosmos-examples/pom.xml @@ -8,12 +8,12 @@ Licensed under the MIT License. com.microsoft.azure azure-cosmos-parent - 3.5.1-beta1 + 3.5.0 com.microsoft.azure azure-cosmos-examples - 3.5.1-beta1 + 3.6.0-beta.2 Microsoft Azure SDK for SQL API of Azure Cosmos DB Service - Examples This package contains examples for Microsoft Azure SDK for SQL API of Azure Cosmos DB Service https://github.com/Azure/azure-sdk-for-java @@ -94,7 +94,7 @@ Licensed under the MIT License. com.microsoft.azure azure-cosmos - 3.5.1-beta1 + 3.6.0-beta.2 diff --git a/sdk/cosmos/microsoft-azure-cosmos/pom.xml b/sdk/cosmos/microsoft-azure-cosmos/pom.xml index 75e5fa0875f6a..17da84c781385 100644 --- a/sdk/cosmos/microsoft-azure-cosmos/pom.xml +++ b/sdk/cosmos/microsoft-azure-cosmos/pom.xml @@ -7,12 +7,12 @@ Licensed under the MIT License. com.microsoft.azure azure-cosmos-parent - 3.5.1-beta1 + 3.5.0 com.microsoft.azure azure-cosmos - 3.5.1-beta1 + 3.6.0-beta.2 Microsoft Azure SDK for SQL API of Azure Cosmos DB Service This Package contains Microsoft Azure Cosmos SDK (with Reactive Extension rx support) for Azure Cosmos DB SQL API jar @@ -36,6 +36,12 @@ Licensed under the MIT License. 2.10.0 + + com.fasterxml.jackson.datatype + jackson-datatype-jsr310 + 2.10.0 + + com.fasterxml.uuid java-uuid-generator diff --git a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java index 0b13cf4aafd04..f16d56835a978 100644 --- a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java +++ b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/HttpConstants.java @@ -257,7 +257,7 @@ public static class Versions { // @see // https://stackoverflow.com/questions/2469922/generate-a-version-java-file-in-maven // {x-version-update-start;com.microsoft.azure:azure-cosmos;current} - public static final String SDK_VERSION = "3.5.1-beta1"; + public static final String SDK_VERSION = "3.6.0-beta.2"; // {x-version-update-end} public static final String SDK_NAME = "cosmosdb-java-sdk"; } diff --git a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java index 930a371e6a79a..ea42e143ae13a 100644 --- a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java +++ b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClient.java @@ -11,6 +11,8 @@ import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequestArgs; import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdRequestRecord; import com.azure.data.cosmos.internal.directconnectivity.rntbd.RntbdServiceEndpoint; +import com.fasterxml.jackson.annotation.JsonIgnore; +import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.core.JsonGenerator; import com.fasterxml.jackson.databind.SerializerProvider; import com.fasterxml.jackson.databind.annotation.JsonSerialize; @@ -23,7 +25,9 @@ import reactor.core.publisher.Mono; import reactor.core.publisher.SignalType; +import java.io.File; import java.io.IOException; +import java.io.InputStream; import java.net.URI; import java.time.Duration; import java.util.Iterator; @@ -158,42 +162,88 @@ public static final class Options { // region Fields + @JsonProperty() private final int bufferPageSize; - private final String certificateHostNameOverride; + + @JsonProperty() private final Duration connectionTimeout; + + @JsonProperty() private final Duration idleChannelTimeout; + + @JsonProperty() private final Duration idleEndpointTimeout; + + @JsonProperty() private final int maxBufferCapacity; + + @JsonProperty() private final int maxChannelsPerEndpoint; + + @JsonProperty() private final int maxRequestsPerChannel; - private final int partitionCount; + + @JsonProperty() private final Duration receiveHangDetectionTime; + + @JsonProperty() private final Duration requestExpiryInterval; + + @JsonProperty() private final Duration requestTimeout; + + @JsonProperty() + private final Duration requestTimerResolution; + + @JsonProperty() private final Duration sendHangDetectionTime; + + @JsonProperty() private final Duration shutdownTimeout; + + @JsonIgnore() private final UserAgentContainer userAgent; // endregion // region Constructors + private Options() { + this.bufferPageSize = 8192; + this.connectionTimeout = null; + this.idleChannelTimeout = Duration.ZERO; + this.idleEndpointTimeout = Duration.ofSeconds(70L); + this.maxBufferCapacity = 8192 << 10; + this.maxChannelsPerEndpoint = 10; + this.maxRequestsPerChannel = 30; + this.receiveHangDetectionTime = Duration.ofSeconds(65L); + this.requestExpiryInterval = Duration.ofSeconds(5L); + this.requestTimeout = null; + this.requestTimerResolution = Duration.ofMillis(5L); + this.sendHangDetectionTime = Duration.ofSeconds(10L); + this.shutdownTimeout = Duration.ofSeconds(15L); + this.userAgent = new UserAgentContainer(); + } + private Options(Builder builder) { + this.bufferPageSize = builder.bufferPageSize; - this.certificateHostNameOverride = builder.certificateHostNameOverride; - this.connectionTimeout = builder.connectionTimeout == null ? builder.requestTimeout : builder.connectionTimeout; this.idleChannelTimeout = builder.idleChannelTimeout; this.idleEndpointTimeout = builder.idleEndpointTimeout; this.maxBufferCapacity = builder.maxBufferCapacity; this.maxChannelsPerEndpoint = builder.maxChannelsPerEndpoint; this.maxRequestsPerChannel = builder.maxRequestsPerChannel; - this.partitionCount = builder.partitionCount; this.receiveHangDetectionTime = builder.receiveHangDetectionTime; this.requestExpiryInterval = builder.requestExpiryInterval; this.requestTimeout = builder.requestTimeout; + this.requestTimerResolution = builder.requestTimerResolution; this.sendHangDetectionTime = builder.sendHangDetectionTime; this.shutdownTimeout = builder.shutdownTimeout; this.userAgent = builder.userAgent; + + this.connectionTimeout = builder.connectionTimeout == null + ? builder.requestTimeout + : builder.connectionTimeout; } // endregion @@ -204,10 +254,6 @@ public int bufferPageSize() { return this.bufferPageSize; } - public String certificateHostNameOverride() { - return this.certificateHostNameOverride; - } - public Duration connectionTimeout() { return this.connectionTimeout; } @@ -232,10 +278,6 @@ public int maxRequestsPerChannel() { return this.maxRequestsPerChannel; } - public int partitionCount() { - return this.partitionCount; - } - public Duration receiveHangDetectionTime() { return this.receiveHangDetectionTime; } @@ -248,6 +290,10 @@ public Duration requestTimeout() { return this.requestTimeout; } + public Duration requestTimerResolution() { + return this.requestTimerResolution; + } + public Duration sendHangDetectionTime() { return this.sendHangDetectionTime; } @@ -273,39 +319,110 @@ public String toString() { // region Types + @SuppressWarnings("UnusedReturnValue") public static class Builder { // region Fields - private static final UserAgentContainer DEFAULT_USER_AGENT_CONTAINER = new UserAgentContainer(); - private static final Duration FIFTEEN_SECONDS = Duration.ofSeconds(15L); - private static final Duration FIVE_SECONDS =Duration.ofSeconds(5L); - private static final Duration SEVENTY_SECONDS = Duration.ofSeconds(70L); - private static final Duration SIXTY_FIVE_SECONDS = Duration.ofSeconds(65L); - private static final Duration TEN_SECONDS = Duration.ofSeconds(10L); - - private int bufferPageSize = 8192; - private String certificateHostNameOverride = null; - private Duration connectionTimeout = null; - private Duration idleChannelTimeout = Duration.ZERO; - private Duration idleEndpointTimeout = SEVENTY_SECONDS; - private int maxBufferCapacity = 8192 << 10; - private int maxChannelsPerEndpoint = 10; - private int maxRequestsPerChannel = 30; - private int partitionCount = 1; - private Duration receiveHangDetectionTime = SIXTY_FIVE_SECONDS; - private Duration requestExpiryInterval = FIVE_SECONDS; + private static final String DEFAULT_OPTIONS_PROPERTY_NAME = "azure.cosmos.directTcp.defaultOptions"; + private static final Options DEFAULT_OPTIONS; + + static { + + // In priority order we take default Direct TCP options from: + // + // 1. the string value of system property "azure.cosmos.directTcp.options", or + // 2. the contents of the file located by the system property "azure.cosmos.directTcp.optionsFile", or + // 3. the contents of the resource file named "azure.cosmos.directTcp.options.json" + // + // Otherwise, if none of these values are set or an error occurs we create default options based on a + // set of hard-wired values defined in the default private parameterless constructor for + // RntbdTransportClient.Options. + + Options options = null; + + try { + final String string = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME); + + if (string != null) { + // Attempt to set default options based on the JSON string value of "{propertyName}" + try { + options = RntbdObjectMapper.readValue(string, Options.class); + } catch (IOException error) { + logger.error("failed to parse default Direct TCP options {} due to ", string, error); + } + } + + if (options == null) { + + final String path = System.getProperty(DEFAULT_OPTIONS_PROPERTY_NAME + "File"); + + if (path != null) { + // Attempt to load default options from the JSON file on the path specified by + // "{propertyName}File" + try { + options = RntbdObjectMapper.readValue(new File(path), Options.class); + } catch (IOException error) { + logger.error("failed to load default Direct TCP options from {} due to ", path, error); + } + } + } + + if (options == null) { + + final ClassLoader loader = RntbdTransportClient.class.getClassLoader(); + final String name = DEFAULT_OPTIONS_PROPERTY_NAME + ".json"; + + try (final InputStream stream = loader.getResourceAsStream(name)) { + if (stream != null) { + // Attempt to load default options from the JSON resource file "{propertyName}.json" + options = RntbdObjectMapper.readValue(stream, Options.class); + } + } catch (IOException error) { + logger.error("failed to load Direct TCP options from resource {} due to ", name, error); + } + } + } finally { + DEFAULT_OPTIONS = options != null ? options : new Options(); + } + } + + private int bufferPageSize; + private Duration connectionTimeout; + private Duration idleChannelTimeout; + private Duration idleEndpointTimeout; + private int maxBufferCapacity; + private int maxChannelsPerEndpoint; + private int maxRequestsPerChannel; + private Duration receiveHangDetectionTime; + private Duration requestExpiryInterval; private Duration requestTimeout; - private Duration sendHangDetectionTime = TEN_SECONDS; - private Duration shutdownTimeout = FIFTEEN_SECONDS; - private UserAgentContainer userAgent = DEFAULT_USER_AGENT_CONTAINER; + private Duration requestTimerResolution; + private Duration sendHangDetectionTime; + private Duration shutdownTimeout; + private UserAgentContainer userAgent; // endregion // region Constructors public Builder(Duration requestTimeout) { + this.requestTimeout(requestTimeout); + + this.bufferPageSize = DEFAULT_OPTIONS.bufferPageSize; + this.connectionTimeout = DEFAULT_OPTIONS.connectionTimeout; + this.idleChannelTimeout = DEFAULT_OPTIONS.idleChannelTimeout; + this.idleEndpointTimeout = DEFAULT_OPTIONS.idleEndpointTimeout; + this.maxBufferCapacity = DEFAULT_OPTIONS.maxBufferCapacity; + this.maxChannelsPerEndpoint = DEFAULT_OPTIONS.maxChannelsPerEndpoint; + this.maxRequestsPerChannel = DEFAULT_OPTIONS.maxRequestsPerChannel; + this.receiveHangDetectionTime = DEFAULT_OPTIONS.receiveHangDetectionTime; + this.requestExpiryInterval = DEFAULT_OPTIONS.requestExpiryInterval; + this.requestTimerResolution = DEFAULT_OPTIONS.requestTimerResolution; + this.sendHangDetectionTime = DEFAULT_OPTIONS.sendHangDetectionTime; + this.shutdownTimeout = DEFAULT_OPTIONS.shutdownTimeout; + this.userAgent = DEFAULT_OPTIONS.userAgent; } public Builder(int requestTimeoutInSeconds) { @@ -332,11 +449,6 @@ public Options build() { return new Options(this); } - public Builder certificateHostNameOverride(final String value) { - this.certificateHostNameOverride = value; - return this; - } - public Builder connectionTimeout(final Duration value) { checkArgument(value == null || value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", @@ -379,12 +491,6 @@ public Builder maxRequestsPerChannel(final int value) { return this; } - public Builder partitionCount(final int value) { - checkArgument(value > 0, "expected positive value, not %s", value); - this.partitionCount = value; - return this; - } - public Builder receiveHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", @@ -409,6 +515,14 @@ public Builder requestTimeout(final Duration value) { return this; } + public Builder requestTimerResolution(final Duration value) { + checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, + "expected positive value, not %s", + value); + this.requestTimerResolution = value; + return this; + } + public Builder sendHangDetectionTime(final Duration value) { checkArgument(value != null && value.compareTo(Duration.ZERO) > 0, "expected positive value, not %s", diff --git a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHealthChecker.java b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHealthChecker.java index 39d09c241a0fc..c1020f01988af 100644 --- a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHealthChecker.java +++ b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdClientChannelHealthChecker.java @@ -32,34 +32,34 @@ public final class RntbdClientChannelHealthChecker implements ChannelHealthCheck private static final Logger logger = LoggerFactory.getLogger(RntbdClientChannelHealthChecker.class); // A channel will be declared healthy if a read succeeded recently as defined by this value. - private static final long recentReadWindow = 1_000_000_000L; + private static final long recentReadWindowInNanos = 1_000_000_000L; // A channel should not be declared unhealthy if a write succeeded recently. As such gaps between // Timestamps.lastChannelWrite and Timestamps.lastChannelRead lower than this value are ignored. // Guidance: The grace period should be large enough to accommodate the round trip time of the slowest server // request. Assuming 1s of network RTT, a 2 MB request, a 2 MB response, a connection that can sustain 1 MB/s // both ways, and a 5-second deadline at the server, 10 seconds should be enough. - private static final long readHangGracePeriod = 10L * 1_000_000_000L; + private static final long readHangGracePeriodInNanos = 10L * 1_000_000_000L; // A channel will not be declared unhealthy if a write was attempted recently. As such gaps between // Timestamps.lastChannelWriteAttempt and Timestamps.lastChannelWrite lower than this value are ignored. // Guidance: The grace period should be large enough to accommodate slow writes. For example, a value of 2s requires // that the client can sustain data rates of at least 1 MB/s when writing 2 MB documents. - private static final long writeHangGracePeriod = 2L * 1_000_000_000L; + private static final long writeHangGracePeriodInNanos = 2L * 1_000_000_000L; // A channel is considered idle if: // idleConnectionTimeout > 0L && System.nanoTime() - Timestamps.lastChannelRead() >= idleConnectionTimeout - private final long idleConnectionTimeout; + private final long idleConnectionTimeoutInNanos; // A channel will be declared unhealthy if the gap between Timestamps.lastChannelWrite and Timestamps.lastChannelRead // grows beyond this value. // Constraint: readDelayLimit > readHangGracePeriod - private final long readDelayLimit; + private final long readDelayLimitInNanos; // A channel will be declared unhealthy if the gap between Timestamps.lastChannelWriteAttempt and Timestamps.lastChannelWrite // grows beyond this value. // Constraint: writeDelayLimit > writeHangGracePeriod - private final long writeDelayLimit; + private final long writeDelayLimitInNanos; // endregion @@ -69,29 +69,29 @@ public RntbdClientChannelHealthChecker(final Config config) { checkNotNull(config, "config: null"); - this.idleConnectionTimeout = config.idleConnectionTimeoutInNanos(); + this.idleConnectionTimeoutInNanos = config.idleConnectionTimeoutInNanos(); - this.readDelayLimit = config.receiveHangDetectionTimeInNanos(); - checkArgument(this.readDelayLimit > readHangGracePeriod, "config.receiveHangDetectionTime: %s", this.readDelayLimit); + this.readDelayLimitInNanos = config.receiveHangDetectionTimeInNanos(); + checkArgument(this.readDelayLimitInNanos > readHangGracePeriodInNanos, "config.receiveHangDetectionTimeInNanos: %s", this.readDelayLimitInNanos); - this.writeDelayLimit = config.sendHangDetectionTimeInNanos(); - checkArgument(this.writeDelayLimit > writeHangGracePeriod, "config.sendHangDetectionTime: %s", this.writeDelayLimit); + this.writeDelayLimitInNanos = config.sendHangDetectionTimeInNanos(); + checkArgument(this.writeDelayLimitInNanos > writeHangGracePeriodInNanos, "config.sendHangDetectionTimeInNanos: %s", this.writeDelayLimitInNanos); } // endregion // region Methods - public long idleConnectionTimeout() { - return this.idleConnectionTimeout; + public long idleConnectionTimeoutInNanos() { + return this.idleConnectionTimeoutInNanos; } - public long readDelayLimit() { - return this.readDelayLimit; + public long readDelayLimitInNanos() { + return this.readDelayLimitInNanos; } - public long writeDelayLimit() { - return this.writeDelayLimit; + public long writeDelayLimitInNanos() { + return this.writeDelayLimitInNanos; } public Future isHealthy(final Channel channel) { @@ -109,7 +109,7 @@ public Future isHealthy(final Channel channel) { final Timestamps timestamps = requestManager.snapshotTimestamps(); final long currentTime = System.nanoTime(); - if (currentTime - timestamps.lastChannelRead() < recentReadWindow) { + if (currentTime - timestamps.lastChannelRead() < recentReadWindowInNanos) { return promise.setSuccess(Boolean.TRUE); // because we recently received data } @@ -119,7 +119,7 @@ public Future isHealthy(final Channel channel) { final long writeDelay = timestamps.lastChannelWriteAttempt() - timestamps.lastChannelWrite(); - if (writeDelay > this.writeDelayLimit && currentTime - timestamps.lastChannelWriteAttempt() > writeHangGracePeriod) { + if (writeDelay > this.writeDelayLimitInNanos && currentTime - timestamps.lastChannelWriteAttempt() > writeHangGracePeriodInNanos) { final Optional rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); @@ -127,7 +127,7 @@ public Future isHealthy(final Channel channel) { logger.warn("{} health check failed due to hung write: {lastChannelWriteAttempt: {}, lastChannelWrite: {}, " + "writeDelay: {}, writeDelayLimit: {}, rntbdContext: {}, pendingRequestCount: {}}", channel, timestamps.lastChannelWriteAttempt(), timestamps.lastChannelWrite(), writeDelay, - this.writeDelayLimit, rntbdContext, pendingRequestCount); + this.writeDelayLimitInNanos, rntbdContext, pendingRequestCount); return promise.setSuccess(Boolean.FALSE); } @@ -138,7 +138,7 @@ public Future isHealthy(final Channel channel) { final long readDelay = timestamps.lastChannelWrite() - timestamps.lastChannelRead(); - if (readDelay > this.readDelayLimit && currentTime - timestamps.lastChannelWrite() > readHangGracePeriod) { + if (readDelay > this.readDelayLimitInNanos && currentTime - timestamps.lastChannelWrite() > readHangGracePeriodInNanos) { final Optional rntbdContext = requestManager.rntbdContext(); final int pendingRequestCount = requestManager.pendingRequestCount(); @@ -146,13 +146,13 @@ public Future isHealthy(final Channel channel) { logger.warn("{} health check failed due to hung read: {lastChannelWrite: {}, lastChannelRead: {}, " + "readDelay: {}, readDelayLimit: {}, rntbdContext: {}, pendingRequestCount: {}}", channel, timestamps.lastChannelWrite(), timestamps.lastChannelRead(), readDelay, - this.readDelayLimit, rntbdContext, pendingRequestCount); + this.readDelayLimitInNanos, rntbdContext, pendingRequestCount); return promise.setSuccess(Boolean.FALSE); } - if (this.idleConnectionTimeout > 0L) { - if (currentTime - timestamps.lastChannelRead() > this.idleConnectionTimeout) { + if (this.idleConnectionTimeoutInNanos > 0L) { + if (currentTime - timestamps.lastChannelRead() > this.idleConnectionTimeoutInNanos) { return promise.setSuccess(Boolean.FALSE); } } @@ -187,9 +187,9 @@ static final class JsonSerializer extends StdSerializer, String> simpleClassNames = new ConcurrentHashMap<>(); private RntbdObjectMapper() { } + public static T readValue(File file, Class type) throws IOException { + checkNotNull(file, "expected non-null file"); + checkNotNull(type, "expected non-null type"); + return objectMapper.readValue(file, type); + } + + public static T readValue(InputStream stream, Class type) throws IOException { + checkNotNull(stream, "expected non-null stream"); + checkNotNull(type, "expected non-null type"); + return objectMapper.readValue(stream, type); + } + + public static T readValue(String string, Class type) throws IOException { + checkNotNull(string, "expected non-null string"); + checkNotNull(type, "expected non-null type"); + return objectMapper.readValue(string, type); + } + public static String toJson(final Object value) { try { return objectWriter.writeValueAsString(value); diff --git a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java index 61123179ffe8f..c952152cc7280 100644 --- a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java +++ b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestRecord.java @@ -159,5 +159,6 @@ public void serialize( generator.writeEndObject(); } } + // endregion } diff --git a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java index 0af684d857b72..5a8793e81d734 100644 --- a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java +++ b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdRequestTimer.java @@ -13,55 +13,34 @@ import java.util.Set; import java.util.concurrent.TimeUnit; -import static com.google.common.base.Strings.lenientFormat; - public final class RntbdRequestTimer implements AutoCloseable { - private static final long FIVE_MILLISECONDS = 5000000L; - private static final Logger logger = LoggerFactory.getLogger(RntbdRequestTimer.class); - private final long requestTimeout; + private final long requestTimeoutInNanos; private final Timer timer; - public RntbdRequestTimer(final long requestTimeout) { - // Inspection of the HashWheelTimer code indicates that our choice of a 5 millisecond timer resolution ensures - // a request will expire within 10 milliseconds of the specified requestTimeout interval. This is because - // cancellation of a timeout takes two timer resolution units to complete. - this.timer = new HashedWheelTimer(FIVE_MILLISECONDS, TimeUnit.NANOSECONDS); - this.requestTimeout = requestTimeout; + public RntbdRequestTimer(final long requestTimeoutInNanos, final long requestTimerResolutionInNanos) { + // The HashWheelTimer code shows that cancellation of a timeout takes two timer resolution units to complete. + this.timer = new HashedWheelTimer(requestTimerResolutionInNanos, TimeUnit.NANOSECONDS); + this.requestTimeoutInNanos = requestTimeoutInNanos; } public long getRequestTimeout(final TimeUnit unit) { - return unit.convert(requestTimeout, TimeUnit.NANOSECONDS); + return unit.convert(requestTimeoutInNanos, TimeUnit.NANOSECONDS); } @Override public void close() { - final Set timeouts = this.timer.stop(); - final int count = timeouts.size(); - - if (count == 0) { - logger.debug("no outstanding request timeout tasks"); - return; - } - - logger.debug("stopping {} request timeout tasks", count); - - for (final Timeout timeout : timeouts) { - if (!timeout.isExpired()) { - try { - timeout.task().run(timeout); - } catch (Throwable error) { - logger.warn(lenientFormat("request timeout task failed due to ", error)); - } + if (logger.isDebugEnabled()) { + final int count = timeouts.size(); + if (count > 0) { + logger.debug("request expiration tasks cancelled: {}", count); } } - - logger.debug("{} request timeout tasks stopped", count); } public Timeout newTimeout(final TimerTask task) { - return this.timer.newTimeout(task, this.requestTimeout, TimeUnit.NANOSECONDS); + return this.timer.newTimeout(task, this.requestTimeoutInNanos, TimeUnit.NANOSECONDS); } } diff --git a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java index e29d654685186..83283f220d98a 100644 --- a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java +++ b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/directconnectivity/rntbd/RntbdServiceEndpoint.java @@ -317,7 +317,7 @@ public Provider(final RntbdTransportClient transportClient, final Options option checkNotNull(sslContext, "expected non-null sslContext"); final DefaultThreadFactory threadFactory = new DefaultThreadFactory("cosmos-rntbd-nio", true); - final int threadCount = 2 * Runtime.getRuntime().availableProcessors(); + final int threadCount = Runtime.getRuntime().availableProcessors(); final LogLevel wireLogLevel; if (logger.isTraceEnabled()) { @@ -330,9 +330,12 @@ public Provider(final RntbdTransportClient transportClient, final Options option this.transportClient = transportClient; this.config = new Config(options, sslContext, wireLogLevel); - this.requestTimer = new RntbdRequestTimer(config.requestTimeoutInNanos()); - this.eventLoopGroup = new NioEventLoopGroup(threadCount, threadFactory); + this.requestTimer = new RntbdRequestTimer( + config.requestTimeoutInNanos(), + config.requestTimerResolutionInNanos()); + + this.eventLoopGroup = new NioEventLoopGroup(threadCount, threadFactory); this.endpoints = new ConcurrentHashMap<>(); this.evictions = new AtomicInteger(); this.closed = new AtomicBoolean(); diff --git a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java index fc318844ecbda..424f4886b779c 100644 --- a/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java +++ b/sdk/cosmos/microsoft-azure-cosmos/src/main/java/com/azure/data/cosmos/internal/http/ReactorNettyClient.java @@ -172,31 +172,22 @@ public HttpHeaders headers() { @Override public Flux body() { - return bodyIntern().doFinally(s -> this.close()); + return bodyIntern(); } @Override public Mono bodyAsByteArray() { - return bodyIntern().aggregate().asByteArray().doFinally(s -> this.close()); + return bodyIntern().aggregate().asByteArray(); } @Override public Mono bodyAsString() { - return bodyIntern().aggregate().asString().doFinally(s -> this.close()); + return bodyIntern().aggregate().asString(); } @Override public Mono bodyAsString(Charset charset) { - return bodyIntern().aggregate().asString(charset).doFinally(s -> this.close()); - } - - @Override - public void close() { - if (reactorNettyConnection.channel().eventLoop().inEventLoop()) { - reactorNettyConnection.dispose(); - } else { - reactorNettyConnection.channel().eventLoop().execute(reactorNettyConnection::dispose); - } + return bodyIntern().aggregate().asString(charset); } private ByteBufFlux bodyIntern() { diff --git a/sdk/cosmos/microsoft-azure-cosmos/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java b/sdk/cosmos/microsoft-azure-cosmos/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java index b6201b086f23e..54eee4424e366 100644 --- a/sdk/cosmos/microsoft-azure-cosmos/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java +++ b/sdk/cosmos/microsoft-azure-cosmos/src/test/java/com/azure/data/cosmos/internal/directconnectivity/RntbdTransportClientTest.java @@ -914,7 +914,9 @@ static class Provider implements RntbdEndpoint.Provider { Provider(RntbdTransportClient.Options options, SslContext sslContext, RntbdResponse expected) { this.config = new Config(options, sslContext, LogLevel.WARN); - this.timer = new RntbdRequestTimer(config.requestTimeoutInNanos()); + this.timer = new RntbdRequestTimer( + config.requestTimeoutInNanos(), + config.requestTimerResolutionInNanos()); this.expected = expected; } diff --git a/sdk/cosmos/pom.xml b/sdk/cosmos/pom.xml index 3d5ed59778a08..e6fe8f8ca8b44 100644 --- a/sdk/cosmos/pom.xml +++ b/sdk/cosmos/pom.xml @@ -13,7 +13,7 @@ Licensed under the MIT License. com.microsoft.azure azure-cosmos-parent - 3.5.1-beta1 + 3.5.0 pom Microsoft Azure Cosmos DB SQL API diff --git a/sdk/e2e/pom.xml b/sdk/e2e/pom.xml index 01d7cf01d21d9..8bac71e7b6aba 100644 --- a/sdk/e2e/pom.xml +++ b/sdk/e2e/pom.xml @@ -23,12 +23,12 @@ com.azure azure-core - 1.2.0-beta.1 + 1.3.0-beta.1 com.azure azure-core-http-netty - 1.2.0-beta.1 + 1.3.0-beta.1 com.azure @@ -38,17 +38,17 @@ com.azure azure-security-keyvault-keys - 4.1.0-beta.1 + 4.1.0 com.azure azure-security-keyvault-secrets - 4.1.0-beta.1 + 4.1.0 com.azure azure-security-keyvault-certificates - 4.0.0-beta.8 + 4.0.0 org.slf4j @@ -59,7 +59,7 @@ com.azure azure-core-test - 1.1.0-beta.2 + 1.2.0-beta.1 test diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/CHANGELOG.md b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/CHANGELOG.md index c9a5c68526f34..56d05dd8004a4 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.0.0-beta.5 (Unreleased) +## 1.0.1 (2020-01-07) ## 1.0.0-beta.4 (2019-12-02) - Artifact name changed from `preview` to `beta`. @@ -23,7 +23,7 @@ our efforts can be found in the [Azure SDK Design Guidelines for Java](https://a - Reactive streams support using [Project Reactor](https://projectreactor.io/). - Receive messages from all partitions of an Azure Event Hub using `EventProcessor`. -- Provide an instance of `BlobCheckpointStore` to your Event Processor. `BlobCheckpointStore` uses Azure Blob Storage to +- Provide an instance of `BlobCheckpointStore` to your Event Processor. `BlobCheckpointStore` uses Azure Blob Storage to store checkpoints and balance partition load among all instances of Event Processors. - Store checkpoint and partition ownership details in [Azure Storage Blobs](https://azure.microsoft.com/en-us/services/storage/blobs/). diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md index a810b0506f3c5..5f0394f62c4b5 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/README.md @@ -30,7 +30,7 @@ All client libraries, by default, use the Tomcat-native Boring SSL library to en com.azure azure-messaging-eventhubs-checkpointstore-blob - 1.0.0-beta.4 + 1.0.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/pom.xml index 25cf73d6e7e9b..496c96601eb1f 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.0.0-beta.5 + 1.0.1 Microsoft Azure client library for storing checkpoints in Storage Blobs Library for using storing checkpoints in Storage Blobs @@ -40,7 +40,7 @@ com.azure azure-messaging-eventhubs - 5.0.0-beta.7 + 5.0.1 com.azure diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/java/com/azure/messaging/eventhubs/checkpointstore/blob/BlobCheckpointStore.java b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/java/com/azure/messaging/eventhubs/checkpointstore/blob/BlobCheckpointStore.java index a4711d3633614..aed945ae82903 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/java/com/azure/messaging/eventhubs/checkpointstore/blob/BlobCheckpointStore.java +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/java/com/azure/messaging/eventhubs/checkpointstore/blob/BlobCheckpointStore.java @@ -41,9 +41,9 @@ */ public class BlobCheckpointStore implements CheckpointStore { - private static final String SEQUENCE_NUMBER = "SequenceNumber"; - private static final String OFFSET = "Offset"; - private static final String OWNER_ID = "OwnerId"; + private static final String SEQUENCE_NUMBER = "sequencenumber"; + private static final String OFFSET = "offset"; + private static final String OWNER_ID = "ownerid"; private static final String ETAG = "eTag"; private static final String BLOB_PATH_SEPARATOR = "/"; @@ -109,14 +109,27 @@ private Mono convertToCheckpoint(BlobItem blobItem) { } Map metadata = blobItem.getMetadata(); + logger.info(Messages.CHECKPOINT_INFO, blobItem.getName(), metadata.get(SEQUENCE_NUMBER), + metadata.get(OFFSET)); + + Long sequenceNumber = null; + Long offset = null; + if (!CoreUtils.isNullOrEmpty(metadata.get(SEQUENCE_NUMBER))) { + sequenceNumber = Long.parseLong(metadata.get(SEQUENCE_NUMBER)); + } + + if (!CoreUtils.isNullOrEmpty(metadata.get(OFFSET))) { + offset = Long.parseLong(metadata.get(OFFSET)); + } + Checkpoint checkpoint = new Checkpoint() .setFullyQualifiedNamespace(names[0]) .setEventHubName(names[1]) .setConsumerGroup(names[2]) // names[3] is "checkpoint" .setPartitionId(names[4]) - .setSequenceNumber(Long.parseLong(metadata.get(SEQUENCE_NUMBER))) - .setOffset(Long.parseLong(metadata.get(OFFSET))); + .setSequenceNumber(sequenceNumber) + .setOffset(offset); return Mono.just(checkpoint); } @@ -134,38 +147,44 @@ private Mono convertToCheckpoint(BlobItem blobItem) { public Flux claimOwnership(List requestedPartitionOwnerships) { return Flux.fromIterable(requestedPartitionOwnerships).flatMap(partitionOwnership -> { - String partitionId = partitionOwnership.getPartitionId(); - String blobName = getBlobName(partitionOwnership.getFullyQualifiedNamespace(), - partitionOwnership.getEventHubName(), partitionOwnership.getConsumerGroup(), partitionId, - OWNERSHIP_PATH); - - if (!blobClients.containsKey(blobName)) { - blobClients.put(blobName, blobContainerAsyncClient.getBlobAsyncClient(blobName)); - } - - BlobAsyncClient blobAsyncClient = blobClients.get(blobName); - - Map metadata = new HashMap<>(); - metadata.put(OWNER_ID, partitionOwnership.getOwnerId()); - - BlobRequestConditions blobRequestConditions = new BlobRequestConditions(); - if (CoreUtils.isNullOrEmpty(partitionOwnership.getETag())) { - // New blob should be created - blobRequestConditions.setIfNoneMatch("*"); - return blobAsyncClient.getBlockBlobAsyncClient() - .uploadWithResponse(Flux.just(UPLOAD_DATA), 0, null, metadata, null, null, blobRequestConditions) - .flatMapMany(response -> updateOwnershipETag(response, partitionOwnership), error -> { - logger.info(Messages.CLAIM_ERROR, partitionId, error.getMessage()); - return Mono.empty(); - }, Mono::empty); - } else { - // update existing blob - blobRequestConditions.setIfMatch(partitionOwnership.getETag()); - return blobAsyncClient.setMetadataWithResponse(metadata, blobRequestConditions) - .flatMapMany(response -> updateOwnershipETag(response, partitionOwnership), error -> { - logger.info(Messages.CLAIM_ERROR, partitionId, error.getMessage()); - return Mono.empty(); - }, Mono::empty); + try { + String partitionId = partitionOwnership.getPartitionId(); + String blobName = getBlobName(partitionOwnership.getFullyQualifiedNamespace(), + partitionOwnership.getEventHubName(), partitionOwnership.getConsumerGroup(), partitionId, + OWNERSHIP_PATH); + + if (!blobClients.containsKey(blobName)) { + blobClients.put(blobName, blobContainerAsyncClient.getBlobAsyncClient(blobName)); + } + + BlobAsyncClient blobAsyncClient = blobClients.get(blobName); + + Map metadata = new HashMap<>(); + metadata.put(OWNER_ID, partitionOwnership.getOwnerId()); + + BlobRequestConditions blobRequestConditions = new BlobRequestConditions(); + if (CoreUtils.isNullOrEmpty(partitionOwnership.getETag())) { + // New blob should be created + blobRequestConditions.setIfNoneMatch("*"); + return blobAsyncClient.getBlockBlobAsyncClient() + .uploadWithResponse(Flux.just(UPLOAD_DATA), 0, null, metadata, null, null, + blobRequestConditions) + .flatMapMany(response -> updateOwnershipETag(response, partitionOwnership), error -> { + logger.info(Messages.CLAIM_ERROR, partitionId, error.getMessage()); + return Mono.empty(); + }, Mono::empty); + } else { + // update existing blob + blobRequestConditions.setIfMatch(partitionOwnership.getETag()); + return blobAsyncClient.setMetadataWithResponse(metadata, blobRequestConditions) + .flatMapMany(response -> updateOwnershipETag(response, partitionOwnership), error -> { + logger.info(Messages.CLAIM_ERROR, partitionId, error); + return Mono.empty(); + }, Mono::empty); + } + } catch (Exception ex) { + logger.warning(Messages.CLAIM_ERROR, partitionOwnership.getPartitionId(), ex); + return Mono.empty(); } }); } @@ -237,6 +256,8 @@ private Mono convertToPartitionOwnership(BlobItem blobItem) logger.warning(Messages.NO_METADATA_AVAILABLE_FOR_BLOB, blobItem.getName()); return Mono.empty(); } + logger + .info(Messages.BLOB_OWNER_INFO, blobItem.getName(), blobItem.getMetadata().getOrDefault(OWNER_ID, "")); BlobItemProperties blobProperties = blobItem.getProperties(); PartitionOwnership partitionOwnership = new PartitionOwnership() @@ -245,7 +266,7 @@ private Mono convertToPartitionOwnership(BlobItem blobItem) .setConsumerGroup(names[2]) // names[3] is "ownership" .setPartitionId(names[4]) - .setOwnerId(blobItem.getMetadata().get(OWNER_ID)) + .setOwnerId(blobItem.getMetadata().getOrDefault(OWNER_ID, "")) .setLastModifiedTime(blobProperties.getLastModified().toInstant().toEpochMilli()) .setETag(blobProperties.getETag()); return Mono.just(partitionOwnership); diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/java/com/azure/messaging/eventhubs/checkpointstore/blob/Messages.java b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/java/com/azure/messaging/eventhubs/checkpointstore/blob/Messages.java index 058f7800f967c..ddf6ac0793017 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/java/com/azure/messaging/eventhubs/checkpointstore/blob/Messages.java +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/java/com/azure/messaging/eventhubs/checkpointstore/blob/Messages.java @@ -18,8 +18,10 @@ public enum Messages { private static Properties properties; private static final String PATH = "com/azure/messaging/eventhubs/checkpointstore/blob/messages.properties"; public static final String NO_METADATA_AVAILABLE_FOR_BLOB = "No metadata available for blob {}"; - public static final String CLAIM_ERROR = "Couldn't claim ownership of partition {}, error {}"; + public static final String CLAIM_ERROR = "Couldn't claim ownership of partition {}"; public static final String FOUND_BLOB_FOR_PARTITION = "Found blob for partition {}"; + public static final String BLOB_OWNER_INFO = "Blob {} is owned by {}"; + public static final String CHECKPOINT_INFO = "Blob {} has checkpoint with sequence number {} and offset {}"; private static synchronized Properties getProperties() { if (properties != null) { diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/resources/com/azure/messaging/eventhubs/checkpointstore/blob/messages.properties b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/resources/com/azure/messaging/eventhubs/checkpointstore/blob/messages.properties index 35583072b0b85..76dcc830fd7b6 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/resources/com/azure/messaging/eventhubs/checkpointstore/blob/messages.properties +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/main/resources/com/azure/messaging/eventhubs/checkpointstore/blob/messages.properties @@ -1,3 +1,5 @@ NO_METADATA_AVAILABLE_FOR_BLOB=No metadata available for blob {} -CLAIM_ERROR=Couldn't claim ownership of partition {}, error {} +CLAIM_ERROR=Couldn't claim ownership of partition {} FOUND_BLOB_FOR_PARTITION=Found blob for partition {} +BLOB_OWNER_INFO=Blob {} is owned by {} +CHECKPOINT_INFO=Blob {} has checkpoint with sequence number {} and offset {} diff --git a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/test/java/com/azure/messaging/eventhubs/checkpointstore/blob/BlobEventProcessorClientStoreTest.java b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/test/java/com/azure/messaging/eventhubs/checkpointstore/blob/BlobEventProcessorClientStoreTest.java index 40df3b74448e8..be5eac43e4854 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/test/java/com/azure/messaging/eventhubs/checkpointstore/blob/BlobEventProcessorClientStoreTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs-checkpointstore-blob/src/test/java/com/azure/messaging/eventhubs/checkpointstore/blob/BlobEventProcessorClientStoreTest.java @@ -210,9 +210,9 @@ private BlobItem getBlobItem(String owner, String sequenceNumber, String offset, private Map getMetadata(String owner, String sequenceNumber, String offset) { Map metadata = new HashMap<>(); - metadata.put("OwnerId", owner); - metadata.put("SequenceNumber", sequenceNumber); - metadata.put("Offset", offset); + metadata.put("ownerid", owner); + metadata.put("sequencenumber", sequenceNumber); + metadata.put("offset", offset); return metadata; } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/CHANGELOG.md b/sdk/eventhubs/azure-messaging-eventhubs/CHANGELOG.md index 29e813cd0b8ed..0364f66df4b76 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/CHANGELOG.md +++ b/sdk/eventhubs/azure-messaging-eventhubs/CHANGELOG.md @@ -1,6 +1,11 @@ # Release History -## 5.0.0-beta.7 (Unreleased) +## 5.0.1 (2020-01-07) +- Add support for different error handling cases in EventProcessor. +- Recreate connection in client on transient errors. +- Add tracing links when sending a batch of events. +- Tracing link names are shortened when sending events. +- EventPosition.fromOffset(long) is no longer inclusive. ## 5.0.0-beta.6 (2019-12-02) - Artifact name changed from `preview` to `beta`. @@ -23,10 +28,10 @@ be declared at the time of receiving events and not when the client is created. - `EventHubProducerAsyncClient` and `EventHubProduderClient` for sending events. - `EventHubConsumerAsyncClient` and `EventHubConsumerClient` for receiving events. - Moved `InMemoryPartitionManager` from main package to samples and renamed to `InMemoryEventProcessorStore` -- The `EventProcessorStore`, previously `PartitionManager`, has updated APIs to include `fullyQualifiedNamespace` of +- The `EventProcessorStore`, previously `PartitionManager`, has updated APIs to include `fullyQualifiedNamespace` of the Event Hub. - Updates to `EventProcessor` to allow functional callbacks for processing events, errors etc. - + ## 5.0.0-preview.4 (2019-10-08) - Proxy support for Event Hubs sync and async clients. - `EventHubConsumer` and `EventHubAsyncConsumer` now provides last enqueued event information. diff --git a/sdk/eventhubs/azure-messaging-eventhubs/README.md b/sdk/eventhubs/azure-messaging-eventhubs/README.md index 1c87bb054a52e..081f4809ad844 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/README.md +++ b/sdk/eventhubs/azure-messaging-eventhubs/README.md @@ -60,7 +60,7 @@ documentation][event_hubs_product_docs] | [Samples][sample_examples] com.azure azure-messaging-eventhubs - 5.0.0-beta.6 + 5.0.1 ``` [//]: # ({x-version-update-end}) @@ -109,7 +109,7 @@ platform. First, add the package: com.azure azure-identity - 1.0.1 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) @@ -141,6 +141,10 @@ EventHubProducerClient client = new EventHubClientBuilder() .buildProducerClient(); ``` +When using Azure Active Directory, your principal must be assigned a role which allows access to Event Hubs, such +as the `Azure Event Hubs Data Owner` role. For more information about using Azure Active Directory authorization +with Event Hubs, please refer to [the associated documentation][aad_authorization]. + ## Key concepts - An **Event Hub producer** is a source of telemetry data, diagnostics information, usage logs, or other log data, as @@ -429,6 +433,7 @@ Guidelines](./CONTRIBUTING.md) for more information. [amqp_transport_error]: https://docs.oasis-open.org/amqp/core/v1.0/os/amqp-core-transport-v1.0-os.html#type-amqp-error +[aad_authorization]: https://docs.microsoft.com/azure/event-hubs/authorize-access-azure-active-directory [api_documentation]: https://aka.ms/java-docs [app_registration_page]: https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#get-values-for-signing-in [application_client_secret]: https://docs.microsoft.com/azure/active-directory/develop/howto-create-service-principal-portal#create-a-new-application-secret diff --git a/sdk/eventhubs/azure-messaging-eventhubs/pom.xml b/sdk/eventhubs/azure-messaging-eventhubs/pom.xml index f4b465c4529f6..de3b6a052a6a6 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.0.0-beta.7 + 5.0.1 Microsoft Azure client library for Event Hubs Libraries built on Microsoft Azure Event Hubs @@ -37,25 +37,25 @@ com.azure azure-core - 1.2.0-beta.1 + 1.2.0 com.azure azure-core-amqp - 1.0.0-beta.9 + 1.0.1 com.azure azure-identity - 1.0.1 + 1.0.2 test com.azure azure-core-test - 1.1.0-beta.1 + 1.1.0 test diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubAsyncClient.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubAsyncClient.java index 6015f6f7d9df8..81e59731f8883 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubAsyncClient.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubAsyncClient.java @@ -6,6 +6,7 @@ import com.azure.core.amqp.implementation.MessageSerializer; import com.azure.core.amqp.implementation.TracerProvider; import com.azure.core.util.logging.ClientLogger; +import com.azure.messaging.eventhubs.implementation.EventHubConnectionProcessor; import com.azure.messaging.eventhubs.implementation.EventHubManagementNode; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; @@ -25,15 +26,16 @@ class EventHubAsyncClient implements Closeable { private final ClientLogger logger = new ClientLogger(EventHubAsyncClient.class); private final MessageSerializer messageSerializer; - private final EventHubConnection connection; + private final EventHubConnectionProcessor connectionProcessor; private final boolean isSharedConnection; private final TracerProvider tracerProvider; - EventHubAsyncClient(EventHubConnection connection, TracerProvider tracerProvider, + EventHubAsyncClient(EventHubConnectionProcessor connectionProcessor, TracerProvider tracerProvider, MessageSerializer messageSerializer, boolean isSharedConnection) { this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); - this.connection = Objects.requireNonNull(connection, "'connection' cannot be null."); + this.connectionProcessor = Objects.requireNonNull(connectionProcessor, + "'connectionProcessor' cannot be null."); this.isSharedConnection = isSharedConnection; } @@ -43,7 +45,7 @@ class EventHubAsyncClient implements Closeable { * @return The fully qualified namespace of this Event Hub. */ String getFullyQualifiedNamespace() { - return connection.getFullyQualifiedNamespace(); + return connectionProcessor.getFullyQualifiedNamespace(); } /** @@ -52,7 +54,7 @@ String getFullyQualifiedNamespace() { * @return The Event Hub name this client interacts with. */ String getEventHubName() { - return connection.getEventHubName(); + return connectionProcessor.getEventHubName(); } /** @@ -61,7 +63,9 @@ String getEventHubName() { * @return The set of information for the Event Hub that this client is associated with. */ Mono getProperties() { - return connection.getManagementNode().flatMap(EventHubManagementNode::getEventHubProperties); + return connectionProcessor + .flatMap(connection -> connection.getManagementNode()) + .flatMap(EventHubManagementNode::getEventHubProperties); } /** @@ -81,7 +85,9 @@ Flux getPartitionIds() { * @return The set of information for the requested partition under the Event Hub this client is associated with. */ Mono getPartitionProperties(String partitionId) { - return connection.getManagementNode().flatMap(node -> node.getPartitionProperties(partitionId)); + return connectionProcessor + .flatMap(connection -> connection.getManagementNode()) + .flatMap(node -> node.getPartitionProperties(partitionId)); } /** @@ -91,8 +97,9 @@ Mono getPartitionProperties(String partitionId) { * @return A new {@link EventHubProducerAsyncClient}. */ EventHubProducerAsyncClient createProducer() { - return new EventHubProducerAsyncClient(connection.getFullyQualifiedNamespace(), getEventHubName(), connection, - connection.getRetryOptions(), tracerProvider, messageSerializer, isSharedConnection); + return new EventHubProducerAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), getEventHubName(), + connectionProcessor, connectionProcessor.getRetryOptions(), tracerProvider, messageSerializer, + isSharedConnection); } /** @@ -115,8 +122,8 @@ EventHubConsumerAsyncClient createConsumer(String consumerGroup, int prefetchCou new IllegalArgumentException("'consumerGroup' cannot be an empty string.")); } - return new EventHubConsumerAsyncClient(connection.getFullyQualifiedNamespace(), getEventHubName(), - connection, messageSerializer, consumerGroup, prefetchCount, isSharedConnection); + return new EventHubConsumerAsyncClient(connectionProcessor.getFullyQualifiedNamespace(), getEventHubName(), + connectionProcessor, messageSerializer, consumerGroup, prefetchCount, isSharedConnection); } /** @@ -126,6 +133,6 @@ EventHubConsumerAsyncClient createConsumer(String consumerGroup, int prefetchCou */ @Override public void close() { - connection.close(); + connectionProcessor.dispose(); } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java index ac1d1366f5e2f..41d6cb298aaa0 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubClientBuilder.java @@ -26,8 +26,10 @@ import com.azure.core.util.tracing.Tracer; import com.azure.messaging.eventhubs.implementation.ClientConstants; import com.azure.messaging.eventhubs.implementation.EventHubAmqpConnection; +import com.azure.messaging.eventhubs.implementation.EventHubConnectionProcessor; import com.azure.messaging.eventhubs.implementation.EventHubReactorAmqpConnection; import com.azure.messaging.eventhubs.implementation.EventHubSharedKeyCredential; +import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; @@ -35,6 +37,7 @@ import java.net.InetSocketAddress; import java.net.Proxy; import java.util.Locale; +import java.util.Map; import java.util.Objects; import java.util.ServiceLoader; @@ -104,6 +107,10 @@ public class EventHubClientBuilder { // Default number of events to fetch when creating the consumer. static final int DEFAULT_PREFETCH_COUNT = 500; + private static final String EVENTHUBS_PROPERTIES_FILE = "azure-messaging-eventhubs.properties"; + private static final String NAME_KEY = "name"; + private static final String VERSION_KEY = "version"; + private static final String UNKNOWN = "UNKNOWN"; private final ClientLogger logger = new ClientLogger(EventHubClientBuilder.class); @@ -120,7 +127,7 @@ public class EventHubClientBuilder { private String fullyQualifiedNamespace; private String eventHubName; private String consumerGroup; - private EventHubConnection eventHubConnection; + private EventHubConnectionProcessor eventHubConnectionProcessor; private int prefetchCount; private boolean isSharedConnection; @@ -454,22 +461,22 @@ EventHubAsyncClient buildAsyncClient() { } if (scheduler == null) { - scheduler = Schedulers.newElastic("event-hubs"); + scheduler = Schedulers.elastic(); } final MessageSerializer messageSerializer = new EventHubMessageSerializer(); - if (isSharedConnection && eventHubConnection == null) { - eventHubConnection = buildConnection(messageSerializer); + if (isSharedConnection && eventHubConnectionProcessor == null) { + eventHubConnectionProcessor = buildConnectionProcessor(messageSerializer); } - final EventHubConnection connection = isSharedConnection - ? eventHubConnection - : buildConnection(messageSerializer); + final EventHubConnectionProcessor processor = isSharedConnection + ? eventHubConnectionProcessor + : buildConnectionProcessor(messageSerializer); final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); - return new EventHubAsyncClient(connection, tracerProvider, messageSerializer, isSharedConnection); + return new EventHubAsyncClient(processor, tracerProvider, messageSerializer, isSharedConnection); } /** @@ -503,7 +510,7 @@ EventHubClient buildClient() { return new EventHubClient(client, retryOptions); } - private EventHubConnection buildConnection(MessageSerializer messageSerializer) { + private EventHubConnectionProcessor buildConnectionProcessor(MessageSerializer messageSerializer) { final ConnectionOptions connectionOptions = getConnectionOptions(); final TokenManagerProvider tokenManagerProvider = new AzureTokenManagerProvider( connectionOptions.getAuthorizationType(), connectionOptions.getFullyQualifiedNamespace(), @@ -511,14 +518,20 @@ private EventHubConnection buildConnection(MessageSerializer messageSerializer) final ReactorProvider provider = new ReactorProvider(); final ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(provider); - final Mono connectionMono = Mono.fromCallable(() -> { + final Map properties = CoreUtils.getProperties(EVENTHUBS_PROPERTIES_FILE); + final String product = properties.getOrDefault(NAME_KEY, UNKNOWN); + final String clientVersion = properties.getOrDefault(VERSION_KEY, UNKNOWN); + + final Flux connectionFlux = Mono.fromCallable(() -> { final String connectionId = StringUtil.getRandomString("MF"); - return new EventHubReactorAmqpConnection(connectionId, connectionOptions, provider, handlerProvider, - tokenManagerProvider, messageSerializer); - }); + return (EventHubAmqpConnection) new EventHubReactorAmqpConnection(connectionId, connectionOptions, provider, + handlerProvider, tokenManagerProvider, messageSerializer, product, clientVersion); + }).repeat(); - return new EventHubConnection(connectionMono, connectionOptions); + return connectionFlux.subscribeWith(new EventHubConnectionProcessor( + connectionOptions.getFullyQualifiedNamespace(), connectionOptions.getEntityPath(), + connectionOptions.getRetry())); } private ConnectionOptions getConnectionOptions() { diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConnection.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConnection.java deleted file mode 100644 index 4b4c41c767974..0000000000000 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConnection.java +++ /dev/null @@ -1,139 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.messaging.eventhubs; - -import com.azure.core.amqp.AmqpConnection; -import com.azure.core.amqp.AmqpRetryOptions; -import com.azure.core.amqp.AmqpRetryPolicy; -import com.azure.core.amqp.exception.AmqpException; -import com.azure.core.amqp.implementation.AmqpReceiveLink; -import com.azure.core.amqp.implementation.AmqpSendLink; -import com.azure.core.amqp.implementation.ConnectionOptions; -import com.azure.core.amqp.implementation.RetryUtil; -import com.azure.core.util.logging.ClientLogger; -import com.azure.messaging.eventhubs.implementation.EventHubAmqpConnection; -import com.azure.messaging.eventhubs.implementation.EventHubManagementNode; -import com.azure.messaging.eventhubs.implementation.EventHubSession; -import com.azure.messaging.eventhubs.models.EventPosition; -import com.azure.messaging.eventhubs.models.ReceiveOptions; -import reactor.core.publisher.Mono; - -import java.io.Closeable; -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Class that manages the connection to Azure Event Hubs. - */ -class EventHubConnection implements Closeable { - private final ClientLogger logger = new ClientLogger(EventHubConnection.class); - private final AtomicBoolean hasConnection = new AtomicBoolean(); - private final ConnectionOptions connectionOptions; - private final Mono currentConnection; - - /** - * Creates a new instance of {@link EventHubConnection}. - */ - EventHubConnection(Mono createConnectionMono, ConnectionOptions connectionOptions) { - this.connectionOptions = connectionOptions; - this.currentConnection = createConnectionMono - .doOnSubscribe(c -> hasConnection.set(true)) - .cache(); - } - - /** - * Gets the fully qualified namespace for the connection. - * - * @return The fully qualified namespace this is connection. - */ - public String getFullyQualifiedNamespace() { - return connectionOptions.getFullyQualifiedNamespace(); - } - - /** - * Gets the name of the Event Hub. - * - * @return The name of the Event Hub. - */ - public String getEventHubName() { - return connectionOptions.getEntityPath(); - } - - AmqpRetryOptions getRetryOptions() { - return connectionOptions.getRetry(); - } - - /** - * Gets the Event Hub management node. - * - * @return The Event Hub management node. - */ - Mono getManagementNode() { - return currentConnection.flatMap(EventHubAmqpConnection::getManagementNode); - } - - /** - * Creates or gets a send link. The same link is returned if there is an existing send link with the same - * {@code linkName}. Otherwise, a new link is created and returned. - * - * @param linkName The name of the link. - * @param entityPath The remote address to connect to for the message broker. - * @param retryOptions Options to use when creating the link. - * - * @return A new or existing send link that is connected to the given {@code entityPath}. - */ - Mono createSendLink(String linkName, String entityPath, AmqpRetryOptions retryOptions) { - return currentConnection.flatMap(connection -> connection.createSession(entityPath)) - .flatMap(session -> { - logger.verbose("Creating producer for {}", entityPath); - final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(retryOptions); - - return session.createProducer(linkName, entityPath, retryOptions.getTryTimeout(), retryPolicy) - .cast(AmqpSendLink.class); - }); - } - - /** - * Creates or gets an existing receive link. The same link is returned if there is an existing receive link with the - * same {@code linkName}. Otherwise, a new link is created and returned. - * - * @param linkName The name of the link. - * @param entityPath The remote address to connect to for the message broker. - * @param eventPosition Position to set the receive link to. - * @param options Consumer options to use when creating the link. - * - * @return A new or existing receive link that is connected to the given {@code entityPath}. - */ - Mono createReceiveLink(String linkName, String entityPath, EventPosition eventPosition, - ReceiveOptions options) { - return currentConnection.flatMap(connection -> connection.createSession(entityPath).cast(EventHubSession.class)) - .flatMap(session -> { - logger.verbose("Creating consumer for path: {}", entityPath); - final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(connectionOptions.getRetry()); - - return session.createConsumer(linkName, entityPath, connectionOptions.getRetry().getTryTimeout(), - retryPolicy, eventPosition, options); - }); - } - - /** - * Disposes of the Event Hub connection. - * - * @throws AmqpException if the connection encountered an exception while closing. - */ - @Override - public void close() { - if (!hasConnection.getAndSet(false)) { - return; - } - - final AmqpConnection connection = currentConnection.block(connectionOptions.getRetry().getTryTimeout()); - if (connection != null) { - connection.close(); - } - - if (connectionOptions.getScheduler() != null && !connectionOptions.getScheduler().isDisposed()) { - connectionOptions.getScheduler().dispose(); - } - } -} diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClient.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClient.java index 2dbd09b4b6c64..f71aa96a6327d 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClient.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClient.java @@ -10,6 +10,7 @@ import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; import com.azure.core.util.logging.ClientLogger; +import com.azure.messaging.eventhubs.implementation.EventHubConnectionProcessor; import com.azure.messaging.eventhubs.implementation.EventHubManagementNode; import com.azure.messaging.eventhubs.models.EventPosition; import com.azure.messaging.eventhubs.models.PartitionEvent; @@ -60,7 +61,7 @@ public class EventHubConsumerAsyncClient implements Closeable { private final ClientLogger logger = new ClientLogger(EventHubConsumerAsyncClient.class); private final String fullyQualifiedNamespace; private final String eventHubName; - private final EventHubConnection connection; + private final EventHubConnectionProcessor connectionProcessor; private final MessageSerializer messageSerializer; private final String consumerGroup; private final int prefetchCount; @@ -72,11 +73,12 @@ public class EventHubConsumerAsyncClient implements Closeable { private final ConcurrentHashMap openPartitionConsumers = new ConcurrentHashMap<>(); - EventHubConsumerAsyncClient(String fullyQualifiedNamespace, String eventHubName, EventHubConnection connection, - MessageSerializer messageSerializer, String consumerGroup, int prefetchCount, boolean isSharedConnection) { + EventHubConsumerAsyncClient(String fullyQualifiedNamespace, String eventHubName, + EventHubConnectionProcessor connectionProcessor, MessageSerializer messageSerializer, String consumerGroup, + int prefetchCount, boolean isSharedConnection) { this.fullyQualifiedNamespace = fullyQualifiedNamespace; this.eventHubName = eventHubName; - this.connection = connection; + this.connectionProcessor = connectionProcessor; this.messageSerializer = messageSerializer; this.consumerGroup = consumerGroup; this.prefetchCount = prefetchCount; @@ -118,7 +120,8 @@ public String getConsumerGroup() { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getEventHubProperties() { - return connection.getManagementNode().flatMap(EventHubManagementNode::getEventHubProperties); + return connectionProcessor.flatMap(connection -> connection.getManagementNode()) + .flatMap(EventHubManagementNode::getEventHubProperties); } /** @@ -148,7 +151,8 @@ public Mono getPartitionProperties(String partitionId) { return monoError(logger, new IllegalArgumentException("'partitionId' cannot be an empty string.")); } - return connection.getManagementNode().flatMap(node -> node.getPartitionProperties(partitionId)); + return connectionProcessor.flatMap(connection -> connection.getManagementNode()) + .flatMap(node -> node.getPartitionProperties(partitionId)); } /** @@ -304,7 +308,7 @@ public void close() { openPartitionConsumers.clear(); if (!isSharedConnection) { - connection.close(); + connectionProcessor.dispose(); } } @@ -333,7 +337,8 @@ private EventHubPartitionAsyncConsumer createPartitionConsumer(String linkName, getEventHubName(), consumerGroup, partitionId); final Mono receiveLinkMono = - connection.createReceiveLink(linkName, entityPath, startingPosition, receiveOptions) + connectionProcessor.flatMap(connection -> + connection.createReceiveLink(linkName, entityPath, startingPosition, receiveOptions)) .doOnNext(next -> logger.verbose("Creating consumer for path: {}", next.getEntityPath())); return new EventHubPartitionAsyncConsumer(receiveLinkMono, messageSerializer, getFullyQualifiedNamespace(), diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClient.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClient.java index 2c8f37fb2a4a4..6f81a61d44ddc 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClient.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClient.java @@ -19,6 +19,7 @@ import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.tracing.ProcessKind; +import com.azure.messaging.eventhubs.implementation.EventHubConnectionProcessor; import com.azure.messaging.eventhubs.implementation.EventHubManagementNode; import com.azure.messaging.eventhubs.models.CreateBatchOptions; import com.azure.messaging.eventhubs.models.SendOptions; @@ -33,8 +34,8 @@ import java.util.HashMap; import java.util.List; import java.util.Locale; +import java.util.Objects; import java.util.Set; -import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicReference; import java.util.function.BiConsumer; @@ -51,8 +52,8 @@ /** * An asynchronous producer responsible for transmitting {@link EventData} to a specific Event Hub, grouped - * together in batches. Depending on the {@link CreateBatchOptions options} specified when creating an - * {@link EventDataBatch}, the events may be automatically routed to an available partition or specific to a partition. + * together in batches. Depending on the {@link CreateBatchOptions options} specified when creating an {@link + * EventDataBatch}, the events may be automatically routed to an available partition or specific to a partition. * *

* Allowing automatic routing of partitions is recommended when: @@ -94,16 +95,11 @@ public class EventHubProducerAsyncClient implements Closeable { private static final SendOptions DEFAULT_SEND_OPTIONS = new SendOptions(); private static final CreateBatchOptions DEFAULT_BATCH_OPTIONS = new CreateBatchOptions(); - /** - * Keeps track of the opened send links. Links are key'd by their entityPath. The send link for allowing the service - * load balance messages is the eventHubName. - */ - private final ConcurrentHashMap openLinks = new ConcurrentHashMap<>(); private final ClientLogger logger = new ClientLogger(EventHubProducerAsyncClient.class); private final AtomicBoolean isDisposed = new AtomicBoolean(); private final String fullyQualifiedNamespace; private final String eventHubName; - private final EventHubConnection connection; + private final EventHubConnectionProcessor connectionProcessor; private final AmqpRetryOptions retryOptions; private final TracerProvider tracerProvider; private final MessageSerializer messageSerializer; @@ -114,15 +110,17 @@ public class EventHubProducerAsyncClient implements Closeable { * when {@link CreateBatchOptions#getPartitionId()} is not null or an empty string. Otherwise, allows the service to * load balance the messages amongst available partitions. */ - EventHubProducerAsyncClient(String fullyQualifiedNamespace, String eventHubName, EventHubConnection connection, - AmqpRetryOptions retryOptions, TracerProvider tracerProvider, MessageSerializer messageSerializer, - boolean isSharedConnection) { - this.fullyQualifiedNamespace = fullyQualifiedNamespace; - this.eventHubName = eventHubName; - this.connection = connection; - this.retryOptions = retryOptions; - this.tracerProvider = tracerProvider; - this.messageSerializer = messageSerializer; + EventHubProducerAsyncClient(String fullyQualifiedNamespace, String eventHubName, + EventHubConnectionProcessor connectionProcessor, AmqpRetryOptions retryOptions, TracerProvider tracerProvider, + MessageSerializer messageSerializer, boolean isSharedConnection) { + this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, + "'fullyQualifiedNamespace' cannot be null."); + this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); + this.connectionProcessor = Objects.requireNonNull(connectionProcessor, + "'connectionProcessor' cannot be null."); + this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); + this.tracerProvider = Objects.requireNonNull(tracerProvider, "'tracerProvider' cannot be null."); + this.messageSerializer = Objects.requireNonNull(messageSerializer, "'messageSerializer' cannot be null."); this.isSharedConnection = isSharedConnection; } @@ -152,7 +150,8 @@ public String getEventHubName() { */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getEventHubProperties() { - return connection.getManagementNode().flatMap(EventHubManagementNode::getEventHubProperties); + return connectionProcessor.flatMap(connection -> connection.getManagementNode()) + .flatMap(EventHubManagementNode::getEventHubProperties); } /** @@ -169,14 +168,13 @@ public Flux getPartitionIds() { * events in the partition event stream. * * @param partitionId The unique identifier of a partition associated with the Event Hub. - * * @return The set of information for the requested partition under the Event Hub this client is associated with. - * * @throws NullPointerException if {@code partitionId} is null. */ @ServiceMethod(returns = ReturnType.SINGLE) public Mono getPartitionProperties(String partitionId) { - return connection.getManagementNode().flatMap(node -> node.getPartitionProperties(partitionId)); + return connectionProcessor.flatMap(connection -> connection.getManagementNode()) + .flatMap(node -> node.getPartitionProperties(partitionId)); } /** @@ -192,9 +190,7 @@ public Mono createBatch() { * Creates an {@link EventDataBatch} configured with the options specified. * * @param options A set of options used to configure the {@link EventDataBatch}. - * * @return A new {@link EventDataBatch} that can fit as many events as the transport allows. - * * @throws NullPointerException if {@code options} is null. */ public Mono createBatch(CreateBatchOptions options) { @@ -253,7 +249,6 @@ public Mono createBatch(CreateBatchOptions options) { *

* * @param event Event to send to the service. - * * @return A {@link Mono} that completes when the event is pushed to the service. */ Mono send(EventData event) { @@ -276,7 +271,6 @@ Mono send(EventData event) { * * @param event Event to send to the service. * @param options The set of options to consider when sending this event. - * * @return A {@link Mono} that completes when the event is pushed to the service. */ Mono send(EventData event, SendOptions options) { @@ -295,7 +289,6 @@ Mono send(EventData event, SendOptions options) { * size is the max amount allowed on the link. * * @param events Events to send to the service. - * * @return A {@link Mono} that completes when all events are pushed to the service. */ Mono send(Iterable events) { @@ -313,7 +306,6 @@ Mono send(Iterable events) { * * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. - * * @return A {@link Mono} that completes when all events are pushed to the service. */ Mono send(Iterable events, SendOptions options) { @@ -332,7 +324,6 @@ Mono send(Iterable events, SendOptions options) { * size is the max amount allowed on the link. * * @param events Events to send to the service. - * * @return A {@link Mono} that completes when all events are pushed to the service. */ Mono send(Flux events) { @@ -350,7 +341,6 @@ Mono send(Flux events) { * * @param events Events to send to the service. * @param options The set of options to consider when sending this batch. - * * @return A {@link Mono} that completes when all events are pushed to the service. */ Mono send(Flux events, SendOptions options) { @@ -367,9 +357,7 @@ Mono send(Flux events, SendOptions options) { * Sends the batch to the associated Event Hub. * * @param batch The batch to send to the service. - * * @return A {@link Mono} that completes when the batch is pushed to the service. - * * @throws NullPointerException if {@code batch} is {@code null}. * @see EventHubProducerAsyncClient#createBatch() * @see EventHubProducerAsyncClient#createBatch(CreateBatchOptions) @@ -490,14 +478,11 @@ private String getLinkName(String partitionId) { private Mono getSendLink(String partitionId) { final String entityPath = getEntityPath(partitionId); - final AmqpSendLink openLink = openLinks.get(entityPath); - if (openLink != null) { - return Mono.just(openLink); - } else { - return connection.createSendLink(getLinkName(partitionId), entityPath, retryOptions) - .map(link -> openLinks.computeIfAbsent(entityPath, unusedKey -> link)); - } + return connectionProcessor + .flatMap(connection -> { + return connection.createSendLink(getLinkName(partitionId), entityPath, retryOptions); + }); } /** @@ -510,11 +495,8 @@ public void close() { return; } - openLinks.forEach((key, value) -> value.close()); - openLinks.clear(); - if (!isSharedConnection) { - connection.close(); + connectionProcessor.dispose(); } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventProcessorClient.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventProcessorClient.java index 52104c1184fd2..5f138fa8a1a55 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventProcessorClient.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventProcessorClient.java @@ -8,7 +8,9 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.PartitionProcessor; import com.azure.messaging.eventhubs.models.ErrorContext; +import com.azure.messaging.eventhubs.models.EventPosition; import java.util.Locale; +import java.util.Map; import java.util.Objects; import java.util.UUID; import java.util.concurrent.ThreadLocalRandom; @@ -40,7 +42,7 @@ public class EventProcessorClient { private final ClientLogger logger = new ClientLogger(EventProcessorClient.class); private final String identifier; - private final AtomicBoolean started = new AtomicBoolean(false); + private final AtomicBoolean isRunning = new AtomicBoolean(false); private final PartitionPumpManager partitionPumpManager; private final PartitionBasedLoadBalancer partitionBasedLoadBalancer; private final CheckpointStore checkpointStore; @@ -55,13 +57,16 @@ public class EventProcessorClient { * @param consumerGroup The consumer group name used in this event processor to consumer events. * @param partitionProcessorFactory The factory to create new partition processor(s). * @param checkpointStore The store used for reading and updating partition ownership and checkpoints. information. - * @param trackLastEnqueuedEventProperties If set to {@code true}, all events received by this - * EventProcessorClient will also include the last enqueued event properties for it's respective partitions. + * @param trackLastEnqueuedEventProperties If set to {@code true}, all events received by this EventProcessorClient + * will also include the last enqueued event properties for it's respective partitions. * @param tracerProvider The tracer implementation. + * @param processError Error handler for any errors that occur outside the context of a partition. + * @param initialPartitionEventPosition Map of initial event positions for partition ids. */ EventProcessorClient(EventHubClientBuilder eventHubClientBuilder, String consumerGroup, - Supplier partitionProcessorFactory, CheckpointStore checkpointStore, - boolean trackLastEnqueuedEventProperties, TracerProvider tracerProvider, Consumer processError) { + Supplier partitionProcessorFactory, CheckpointStore checkpointStore, + boolean trackLastEnqueuedEventProperties, TracerProvider tracerProvider, Consumer processError, + Map initialPartitionEventPosition) { Objects.requireNonNull(eventHubClientBuilder, "eventHubClientBuilder cannot be null."); Objects.requireNonNull(consumerGroup, "consumerGroup cannot be null."); @@ -71,7 +76,7 @@ public class EventProcessorClient { this.identifier = UUID.randomUUID().toString(); logger.info("The instance ID for this event processors is {}", this.identifier); this.partitionPumpManager = new PartitionPumpManager(checkpointStore, partitionProcessorFactory, - eventHubClientBuilder, trackLastEnqueuedEventProperties, tracerProvider); + eventHubClientBuilder, trackLastEnqueuedEventProperties, tracerProvider, initialPartitionEventPosition); EventHubAsyncClient eventHubAsyncClient = eventHubClientBuilder.buildAsyncClient(); this.partitionBasedLoadBalancer = new PartitionBasedLoadBalancer(this.checkpointStore, eventHubAsyncClient, @@ -103,7 +108,7 @@ public String getIdentifier() { * {@codesnippet com.azure.messaging.eventhubs.eventprocessorclient.startstop} */ public synchronized void start() { - if (!started.compareAndSet(false, true)) { + if (!isRunning.compareAndSet(false, true)) { logger.info("Event processor is already running"); return; } @@ -127,7 +132,7 @@ public synchronized void start() { * {@codesnippet com.azure.messaging.eventhubs.eventprocessorclient.startstop} */ public synchronized void stop() { - if (!started.compareAndSet(true, false)) { + if (!isRunning.compareAndSet(true, false)) { logger.info("Event processor has already stopped"); return; } @@ -135,4 +140,14 @@ public synchronized void stop() { scheduler.get().dispose(); this.partitionPumpManager.stopAllPartitionPumps(); } + + /** + * Returns {@code true} if the event processor is running. If the event processor is already running, calling + * {@link #start()} has no effect. + * + * @return {@code true} if the event processor is running. + */ + public synchronized boolean isRunning() { + return isRunning.get(); + } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventProcessorClientBuilder.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventProcessorClientBuilder.java index daafe27c3d680..1b1d0637b8df2 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventProcessorClientBuilder.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/EventProcessorClientBuilder.java @@ -19,6 +19,8 @@ import com.azure.messaging.eventhubs.models.EventPosition; import com.azure.messaging.eventhubs.models.ErrorContext; import com.azure.messaging.eventhubs.models.InitializationContext; +import java.util.HashMap; +import java.util.Map; import java.util.Objects; import java.util.ServiceLoader; import java.util.function.Consumer; @@ -73,6 +75,7 @@ public class EventProcessorClientBuilder { private Consumer processPartitionInitialization; private Consumer processPartitionClose; private boolean trackLastEnqueuedEventProperties; + private Map initialPartitionEventPosition = new HashMap<>(); /** * Creates a new instance of {@link EventProcessorClientBuilder}. @@ -289,7 +292,6 @@ public EventProcessorClientBuilder processPartitionClose(Consumer * * @param trackLastEnqueuedEventProperties {@code true} if the resulting events will keep track of the last * enqueued information for that partition; {@code false} otherwise. - * * @return The updated {@link EventProcessorClientBuilder} instance. */ public EventProcessorClientBuilder trackLastEnqueuedEventProperties(boolean trackLastEnqueuedEventProperties) { @@ -297,6 +299,23 @@ public EventProcessorClientBuilder trackLastEnqueuedEventProperties(boolean trac return this; } + /** + * Sets the map containing the event position to use for each partition if a checkpoint for the partition does not + * exist in {@link CheckpointStore}. This map is keyed off of the partition id. If there is no checkpoint in + * {@link CheckpointStore} and there is no entry in this map, the processing of the partition will start from + * {@link EventPosition#latest() latest} position. + * + * @param initialPartitionEventPosition Map of initial event positions for partition ids. + * @return The updated {@link EventProcessorClientBuilder} instance. + */ + public EventProcessorClientBuilder initialPartitionEventPosition( + Map initialPartitionEventPosition) { + + this.initialPartitionEventPosition = Objects.requireNonNull(initialPartitionEventPosition, + "'initialPartitionEventPosition' cannot be null."); + return this; + } + /** * This will create a new {@link EventProcessorClient} configured with the options set in this builder. Each call to * this method will return a new instance of {@link EventProcessorClient}. @@ -322,7 +341,7 @@ public EventProcessorClient buildEventProcessorClient() { final TracerProvider tracerProvider = new TracerProvider(ServiceLoader.load(Tracer.class)); return new EventProcessorClient(eventHubClientBuilder, this.consumerGroup, getPartitionProcessorSupplier(), checkpointStore, trackLastEnqueuedEventProperties, tracerProvider, - processError); + processError, initialPartitionEventPosition); } private Supplier getPartitionProcessorSupplier() { diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancer.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancer.java index 5a89d6d498f08..8026ae465bcb6 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancer.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancer.java @@ -205,9 +205,14 @@ private Mono loadBalance(final Tuple2, Lis if (isLoadBalanced(minPartitionsPerEventProcessor, numberOfEventProcessorsWithAdditionalPartition, ownerPartitionMap)) { // If the partitions are evenly distributed among all active event processors, no change required. - logger.info("Load is balanced"); + logger.info("Load is balanced with this event processor owning {} partitions", + ownerPartitionMap.get(ownerId).size()); // renew ownership of already owned partitions - checkpointStore.claimOwnership(ownerPartitionMap.get(this.ownerId)).subscribe(); + checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet() + .stream() + .map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId)) + .collect(Collectors.toList())) + .subscribe(); return; } @@ -216,14 +221,19 @@ private Mono loadBalance(final Tuple2, Lis logger.info("This event processor owns {} partitions and shouldn't own more", ownerPartitionMap.get(ownerId).size()); // renew ownership of already owned partitions - checkpointStore.claimOwnership(ownerPartitionMap.get(this.ownerId)).subscribe(); + checkpointStore.claimOwnership(partitionPumpManager.getPartitionPumps().keySet() + .stream() + .map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId)) + .collect(Collectors.toList())) + .subscribe(); return; } // If we have reached this stage, this event processor has to claim/steal ownership of at least 1 // more partition logger.info( - "Load is unbalanced and this event processor should own more partitions"); + "Load is unbalanced and this event processor owns {} partitions and should own more partitions", + ownerPartitionMap.get(ownerId).size()); /* * If some partitions are unclaimed, this could be because an event processor is down and * it's partitions are now available for others to own or because event processors are just @@ -345,11 +355,16 @@ private void claimOwnership(final Map partitionOwner PartitionOwnership ownershipRequest = createPartitionOwnershipRequest(partitionOwnershipMap, partitionIdToClaim); - List currentPartitionsOwned = ownerPartitionsMap.get(ownerId); - currentPartitionsOwned.add(ownershipRequest); + List partitionsToClaim = new ArrayList<>(); + partitionsToClaim.add(ownershipRequest); + partitionsToClaim.addAll(partitionPumpManager.getPartitionPumps() + .keySet() + .stream() + .map(partitionId -> createPartitionOwnershipRequest(partitionOwnershipMap, partitionId)) + .collect(Collectors.toList())); checkpointStore - .claimOwnership(currentPartitionsOwned) + .claimOwnership(partitionsToClaim) .timeout(Duration.ofMinutes(1)) // TODO: configurable .doOnNext(partitionOwnership -> logger.info("Successfully claimed ownership of partition {}", partitionOwnership.getPartitionId())) diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionPumpManager.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionPumpManager.java index a620f1392c2ec..77ee1126ef568 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionPumpManager.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/PartitionPumpManager.java @@ -14,6 +14,7 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.core.util.tracing.ProcessKind; import com.azure.messaging.eventhubs.implementation.PartitionProcessor; +import com.azure.messaging.eventhubs.implementation.PartitionProcessorException; import com.azure.messaging.eventhubs.models.Checkpoint; import com.azure.messaging.eventhubs.models.CloseContext; import com.azure.messaging.eventhubs.models.CloseReason; @@ -22,6 +23,7 @@ import com.azure.messaging.eventhubs.models.EventPosition; import com.azure.messaging.eventhubs.models.InitializationContext; import com.azure.messaging.eventhubs.models.PartitionContext; +import com.azure.messaging.eventhubs.models.PartitionEvent; import com.azure.messaging.eventhubs.models.PartitionOwnership; import com.azure.messaging.eventhubs.models.ReceiveOptions; import java.io.Closeable; @@ -53,6 +55,7 @@ class PartitionPumpManager { private final EventHubClientBuilder eventHubClientBuilder; private final TracerProvider tracerProvider; private final boolean trackLastEnqueuedEventProperties; + private final Map initialPartitionEventPosition; /** * Creates an instance of partition pump manager. @@ -65,15 +68,18 @@ class PartitionPumpManager { * @param trackLastEnqueuedEventProperties If set to {@code true}, all events received by this EventProcessorClient * will also include the last enqueued event properties for it's respective partitions. * @param tracerProvider The tracer implementation. + * @param initialPartitionEventPosition Map of initial event positions for partition ids. */ PartitionPumpManager(CheckpointStore checkpointStore, Supplier partitionProcessorFactory, EventHubClientBuilder eventHubClientBuilder, - boolean trackLastEnqueuedEventProperties, TracerProvider tracerProvider) { + boolean trackLastEnqueuedEventProperties, TracerProvider tracerProvider, + Map initialPartitionEventPosition) { this.checkpointStore = checkpointStore; this.partitionProcessorFactory = partitionProcessorFactory; this.eventHubClientBuilder = eventHubClientBuilder; this.trackLastEnqueuedEventProperties = trackLastEnqueuedEventProperties; this.tracerProvider = tracerProvider; + this.initialPartitionEventPosition = initialPartitionEventPosition; } /** @@ -104,83 +110,115 @@ void startPartitionPump(PartitionOwnership claimedOwnership, Checkpoint checkpoi return; } - PartitionContext partitionContext = new PartitionContext(claimedOwnership.getFullyQualifiedNamespace(), - claimedOwnership.getEventHubName(), claimedOwnership.getConsumerGroup(), - claimedOwnership.getPartitionId()); - PartitionProcessor partitionProcessor = this.partitionProcessorFactory.get(); - - InitializationContext initializationContext = new InitializationContext(partitionContext, - EventPosition.earliest()); - partitionProcessor.initialize(initializationContext); - - EventPosition startFromEventPosition = null; - // A checkpoint indicates the last known successfully processed event. - // So, the event position to start a new partition processing should be exclusive of the - // offset/sequence number in the checkpoint. If no checkpoint is available, start from - // the position in set in the InitializationContext (either the earliest event in the partition or - // the user provided initial position) - if (checkpoint != null && checkpoint.getOffset() != null) { - startFromEventPosition = EventPosition.fromOffset(checkpoint.getOffset()); - } else if (checkpoint != null && checkpoint.getSequenceNumber() != null) { - startFromEventPosition = EventPosition.fromSequenceNumber(checkpoint.getSequenceNumber()); - } else { - startFromEventPosition = initializationContext.getInitialPosition(); + try { + PartitionContext partitionContext = new PartitionContext(claimedOwnership.getFullyQualifiedNamespace(), + claimedOwnership.getEventHubName(), claimedOwnership.getConsumerGroup(), + claimedOwnership.getPartitionId()); + PartitionProcessor partitionProcessor = this.partitionProcessorFactory.get(); + + InitializationContext initializationContext = new InitializationContext(partitionContext); + partitionProcessor.initialize(initializationContext); + + EventPosition startFromEventPosition = null; + // A checkpoint indicates the last known successfully processed event. + // So, the event position to start a new partition processing should be exclusive of the + // offset/sequence number in the checkpoint. If no checkpoint is available, start from + // the position in set in the InitializationContext (either the earliest event in the partition or + // the user provided initial position) + if (checkpoint != null && checkpoint.getOffset() != null) { + startFromEventPosition = EventPosition.fromOffset(checkpoint.getOffset()); + } else if (checkpoint != null && checkpoint.getSequenceNumber() != null) { + startFromEventPosition = EventPosition.fromSequenceNumber(checkpoint.getSequenceNumber()); + } else if (initialPartitionEventPosition.containsKey(claimedOwnership.getPartitionId())) { + startFromEventPosition = initialPartitionEventPosition.get(claimedOwnership.getPartitionId()); + } else { + startFromEventPosition = EventPosition.latest(); + } + + ReceiveOptions receiveOptions = new ReceiveOptions().setOwnerLevel(0L) + .setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties); + + EventHubConsumerAsyncClient eventHubConsumer = eventHubClientBuilder.buildAsyncClient() + .createConsumer(claimedOwnership.getConsumerGroup(), EventHubClientBuilder.DEFAULT_PREFETCH_COUNT); + + partitionPumps.put(claimedOwnership.getPartitionId(), eventHubConsumer); + eventHubConsumer + .receiveFromPartition(claimedOwnership.getPartitionId(), startFromEventPosition, receiveOptions) + .subscribe(partitionEvent -> processEvent(partitionContext, partitionProcessor, eventHubConsumer, + partitionEvent), + /* EventHubConsumer receive() returned an error */ + ex -> handleError(claimedOwnership, eventHubConsumer, partitionProcessor, ex, partitionContext), + () -> { + partitionProcessor.close(new CloseContext(partitionContext, + CloseReason.EVENT_PROCESSOR_SHUTDOWN)); + cleanup(claimedOwnership, eventHubConsumer); + }); + } catch (Exception ex) { + if (partitionPumps.containsKey(claimedOwnership.getPartitionId())) { + cleanup(claimedOwnership, partitionPumps.get(claimedOwnership.getPartitionId())); + } + throw logger.logExceptionAsError( + new PartitionProcessorException( + "Error occurred while starting partition pump for partition " + claimedOwnership.getPartitionId(), + ex)); } - ReceiveOptions receiveOptions = new ReceiveOptions().setOwnerLevel(0L) - .setTrackLastEnqueuedEventProperties(trackLastEnqueuedEventProperties); - - EventHubConsumerAsyncClient eventHubConsumer = eventHubClientBuilder.buildAsyncClient() - .createConsumer(claimedOwnership.getConsumerGroup(), EventHubClientBuilder.DEFAULT_PREFETCH_COUNT); - - partitionPumps.put(claimedOwnership.getPartitionId(), eventHubConsumer); - - // The indentation required by checkstyle is different from the indentation IntelliJ uses. - // @formatter:off - eventHubConsumer.receiveFromPartition(claimedOwnership.getPartitionId(), startFromEventPosition, receiveOptions) - .subscribe(partitionEvent -> { - EventData eventData = partitionEvent.getData(); - Context processSpanContext = startProcessTracingSpan(eventData, eventHubConsumer.getEventHubName(), - eventHubConsumer.getFullyQualifiedNamespace()); - if (processSpanContext.getData(SPAN_CONTEXT_KEY).isPresent()) { - eventData.addContext(SPAN_CONTEXT_KEY, processSpanContext); - } - try { - partitionProcessor.processEvent(new EventContext(partitionContext, eventData, checkpointStore, - partitionEvent.getLastEnqueuedEventProperties())); - endProcessTracingSpan(processSpanContext, Signal.complete()); - } catch (Throwable throwable) { - /* user code for event processing threw an exception - log and bubble up */ - endProcessTracingSpan(processSpanContext, Signal.error(throwable)); - throw logger.logExceptionAsError(new RuntimeException("Error in event processing callback", - throwable)); - } - }, /* EventHubConsumer receive() returned an error */ - ex -> handleReceiveError(claimedOwnership, eventHubConsumer, partitionProcessor, ex, partitionContext), - () -> partitionProcessor.close(new CloseContext(partitionContext, - CloseReason.EVENT_PROCESSOR_SHUTDOWN))); - // @formatter:on } - private void handleReceiveError(PartitionOwnership claimedOwnership, EventHubConsumerAsyncClient eventHubConsumer, - PartitionProcessor partitionProcessor, Throwable throwable, PartitionContext partitionContext) { + private void processEvent(PartitionContext partitionContext, PartitionProcessor partitionProcessor, + EventHubConsumerAsyncClient eventHubConsumer, PartitionEvent partitionEvent) { + EventData eventData = partitionEvent.getData(); + Context processSpanContext = startProcessTracingSpan(eventData, eventHubConsumer.getEventHubName(), + eventHubConsumer.getFullyQualifiedNamespace()); + if (processSpanContext.getData(SPAN_CONTEXT_KEY).isPresent()) { + eventData.addContext(SPAN_CONTEXT_KEY, processSpanContext); + } try { - logger.warning("Error receiving events for partition {}", partitionContext.getPartitionId(), throwable); - // if there was an error on receive, it also marks the end of the event data stream + partitionProcessor.processEvent(new EventContext(partitionContext, eventData, checkpointStore, + partitionEvent.getLastEnqueuedEventProperties())); + endProcessTracingSpan(processSpanContext, Signal.complete()); + } catch (Throwable throwable) { + /* user code for event processing threw an exception - log and bubble up */ + endProcessTracingSpan(processSpanContext, Signal.error(throwable)); + throw logger.logExceptionAsError(new PartitionProcessorException("Error in event processing callback", + throwable)); + } + } + + Map getPartitionPumps() { + return this.partitionPumps; + } + + private void handleError(PartitionOwnership claimedOwnership, EventHubConsumerAsyncClient eventHubConsumer, + PartitionProcessor partitionProcessor, Throwable throwable, PartitionContext partitionContext) { + boolean shouldRethrow = true; + if (!(throwable instanceof PartitionProcessorException)) { + shouldRethrow = false; + // If user code threw an exception in processEvent callback, bubble up the exception + logger.warning("Error receiving events from partition {}", partitionContext.getPartitionId(), throwable); partitionProcessor.processError(new ErrorContext(partitionContext, throwable)); - // Any exception while receiving events will result in the processor losing ownership - CloseReason closeReason = CloseReason.LOST_PARTITION_OWNERSHIP; - partitionProcessor.close(new CloseContext(partitionContext, closeReason)); - } catch (Exception ex) { - logger.warning(Messages.FAILED_PROCESSING_ERROR_RECEIVE, claimedOwnership.getPartitionId(), ex); + } + // If there was an error on receive, it also marks the end of the event data stream + // Any exception while receiving events will result in the processor losing ownership + CloseReason closeReason = CloseReason.LOST_PARTITION_OWNERSHIP; + partitionProcessor.close(new CloseContext(partitionContext, closeReason)); + cleanup(claimedOwnership, eventHubConsumer); + if (shouldRethrow) { + PartitionProcessorException exception = (PartitionProcessorException) throwable; + throw logger.logExceptionAsError(exception); + } + } + + private void cleanup(PartitionOwnership claimedOwnership, EventHubConsumerAsyncClient eventHubConsumer) { + try { + // close the consumer + logger.info("Closing consumer for partition id {}", claimedOwnership.getPartitionId()); + eventHubConsumer.close(); } finally { - try { - // close the consumer - eventHubConsumer.close(); - } finally { - // finally, remove the partition from partitionPumps map - partitionPumps.remove(claimedOwnership.getPartitionId()); - } + // finally, remove the partition from partitionPumps map + logger.info("Removing partition id {} from list of processing partitions", + claimedOwnership.getPartitionId()); + partitionPumps.remove(claimedOwnership.getPartitionId()); } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubAmqpConnection.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubAmqpConnection.java index efa2ed2303f98..e992419c41ba5 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubAmqpConnection.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubAmqpConnection.java @@ -4,6 +4,11 @@ package com.azure.messaging.eventhubs.implementation; import com.azure.core.amqp.AmqpConnection; +import com.azure.core.amqp.AmqpRetryOptions; +import com.azure.core.amqp.implementation.AmqpReceiveLink; +import com.azure.core.amqp.implementation.AmqpSendLink; +import com.azure.messaging.eventhubs.models.EventPosition; +import com.azure.messaging.eventhubs.models.ReceiveOptions; import reactor.core.publisher.Mono; /** @@ -16,4 +21,28 @@ public interface EventHubAmqpConnection extends AmqpConnection { * @return A Mono that completes with a session to the Event Hub's management node. */ Mono getManagementNode(); + + /** + * Creates or gets a send link. The same link is returned if there is an existing send link with the same {@code + * linkName}. Otherwise, a new link is created and returned. + * + * @param linkName The name of the link. + * @param entityPath The remote address to connect to for the message broker. + * @param retryOptions Options to use when creating the link. + * @return A new or existing send link that is connected to the given {@code entityPath}. + */ + Mono createSendLink(String linkName, String entityPath, AmqpRetryOptions retryOptions); + + /** + * Creates or gets an existing receive link. The same link is returned if there is an existing receive link with the + * same {@code linkName}. Otherwise, a new link is created and returned. + * + * @param linkName The name of the link. + * @param entityPath The remote address to connect to for the message broker. + * @param eventPosition Position to set the receive link to. + * @param options Consumer options to use when creating the link. + * @return A new or existing receive link that is connected to the given {@code entityPath}. + */ + Mono createReceiveLink(String linkName, String entityPath, EventPosition eventPosition, + ReceiveOptions options); } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubConnectionProcessor.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubConnectionProcessor.java new file mode 100644 index 0000000000000..e7e206bd1479b --- /dev/null +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubConnectionProcessor.java @@ -0,0 +1,307 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventhubs.implementation; + +import com.azure.core.amqp.AmqpEndpointState; +import com.azure.core.amqp.AmqpRetryOptions; +import com.azure.core.amqp.AmqpRetryPolicy; +import com.azure.core.amqp.implementation.RetryUtil; +import com.azure.core.util.logging.ClientLogger; +import org.reactivestreams.Processor; +import org.reactivestreams.Subscription; +import reactor.core.CoreSubscriber; +import reactor.core.Disposable; +import reactor.core.publisher.Mono; +import reactor.core.publisher.Operators; + +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.ConcurrentLinkedDeque; +import java.util.concurrent.atomic.AtomicBoolean; +import java.util.concurrent.atomic.AtomicInteger; + +/** + * Subscribes to an upstream Mono that creates {@link EventHubAmqpConnection} then publishes the created connection + * until it closes then recreates it. + */ +public class EventHubConnectionProcessor extends Mono + implements Processor, CoreSubscriber, + Disposable { + + private final ClientLogger logger = new ClientLogger(EventHubConnectionProcessor.class); + private final AtomicBoolean isTerminated = new AtomicBoolean(); + private final AtomicBoolean isRequested = new AtomicBoolean(); + private final AtomicInteger retryAttempts = new AtomicInteger(); + private final Object lock = new Object(); + private final String fullyQualifiedNamespace; + private final String eventHubName; + private final AmqpRetryOptions retryOptions; + private final AmqpRetryPolicy retryPolicy; + + private Subscription upstream; + private EventHubAmqpConnection currentConnection; + + private volatile ConcurrentLinkedDeque subscribers = new ConcurrentLinkedDeque<>(); + private volatile Throwable lastError; + private volatile Disposable connectionSubscription; + private volatile Disposable retrySubscription; + + public EventHubConnectionProcessor(String fullyQualifiedNamespace, String eventHubName, + AmqpRetryOptions retryOptions) { + this.fullyQualifiedNamespace = Objects.requireNonNull(fullyQualifiedNamespace, + "'fullyQualifiedNamespace' cannot be null."); + this.eventHubName = Objects.requireNonNull(eventHubName, "'eventHubName' cannot be null."); + this.retryOptions = Objects.requireNonNull(retryOptions, "'retryOptions' cannot be null."); + + this.retryPolicy = RetryUtil.getRetryPolicy(retryOptions); + } + + /** + * Gets the fully qualified namespace for the connection. + * + * @return The fully qualified namespace this is connection. + */ + public String getFullyQualifiedNamespace() { + return fullyQualifiedNamespace; + } + + /** + * Gets the name of the Event Hub. + * + * @return The name of the Event Hub. + */ + public String getEventHubName() { + return eventHubName; + } + + public AmqpRetryOptions getRetryOptions() { + return retryOptions; + } + + @Override + public void onSubscribe(Subscription subscription) { + logger.verbose("Subscribing to upstream for connections."); + + this.upstream = subscription; + + // Don't request an EventHubAmqpConnection until there is a subscriber. + subscription.request(0); + } + + @Override + public void onNext(EventHubAmqpConnection eventHubAmqpConnection) { + logger.info("Setting next AMQP connection."); + + Objects.requireNonNull(eventHubAmqpConnection, "'eventHubAmqpConnection' cannot be null."); + + final EventHubAmqpConnection oldConnection; + final Disposable oldSubscription; + synchronized (lock) { + oldConnection = currentConnection; + oldSubscription = connectionSubscription; + + currentConnection = eventHubAmqpConnection; + + final ConcurrentLinkedDeque currentSubscribers = subscribers; + subscribers = new ConcurrentLinkedDeque<>(); + + currentSubscribers.forEach(subscription -> subscription.onNext(eventHubAmqpConnection)); + + connectionSubscription = eventHubAmqpConnection.getEndpointStates().subscribe( + state -> { + // Connection was successfully opened, we can reset the retry interval. + if (state == AmqpEndpointState.ACTIVE) { + retryAttempts.set(0); + } + }, + error -> { + synchronized (lock) { + currentConnection = null; + } + onError(error); + }, + () -> { + if (isDisposed()) { + logger.info("Connection is disposed."); + } else { + logger.info("Connection closed."); + currentConnection = null; + } + }); + } + + if (oldConnection != null) { + oldConnection.close(); + } + + if (oldSubscription != null) { + oldSubscription.dispose(); + } + + isRequested.set(false); + } + + @Override + public void onError(Throwable throwable) { + Objects.requireNonNull(throwable, "'throwable' is required."); + + final int attempt = retryAttempts.incrementAndGet(); + final Duration retryInterval = retryPolicy.calculateRetryDelay(throwable, attempt); + + if (retryInterval != null) { + logger.warning("Transient error occurred. Attempt: {}. Retrying after {} ms.", + attempt, retryInterval.toMillis(), throwable); + + retrySubscription = Mono.delay(retryInterval).subscribe(i -> { + requestUpstream(); + }); + + return; + } + + logger.warning("Non-retryable error occurred in connection.", throwable); + lastError = throwable; + isTerminated.set(true); + dispose(); + + synchronized (lock) { + final ConcurrentLinkedDeque currentSubscribers = subscribers; + subscribers = new ConcurrentLinkedDeque<>(); + + currentSubscribers.forEach(subscriber -> subscriber.onError(throwable)); + } + } + + @Override + public void onComplete() { + logger.info("Upstream connection publisher was completed. Terminating processor."); + + isTerminated.set(true); + synchronized (lock) { + final ConcurrentLinkedDeque currentSubscribers = subscribers; + subscribers = new ConcurrentLinkedDeque<>(); + + currentSubscribers.forEach(subscriber -> subscriber.onComplete()); + } + } + + @Override + public void subscribe(CoreSubscriber actual) { + logger.verbose("Subscription received."); + + final ConnectionSubscriber subscriber = new ConnectionSubscriber(actual, this); + actual.onSubscribe(subscriber); + + if (isTerminated.get()) { + if (lastError != null) { + logger.info("Processor is already terminated. Propagating error."); + subscriber.onError(lastError); + } else { + logger.info("Processor is already terminated. Propagating complete."); + subscriber.onComplete(); + } + + return; + } + + synchronized (lock) { + if (currentConnection != null) { + subscriber.complete(currentConnection); + return; + } + } + + subscribers.add(subscriber); + requestUpstream(); + } + + @Override + public void dispose() { + if (isTerminated.getAndSet(true)) { + return; + } + + if (retrySubscription != null && !retrySubscription.isDisposed()) { + retrySubscription.dispose(); + } + + onComplete(); + + synchronized (lock) { + if (currentConnection != null) { + currentConnection.close(); + } + + currentConnection = null; + } + } + + @Override + public boolean isDisposed() { + return isTerminated.get(); + } + + private void requestUpstream() { + synchronized (lock) { + if (currentConnection != null) { + logger.info("Connection exists, not requesting another."); + return; + } else if (isTerminated.get() || upstream == null) { + logger.verbose("Terminated. Not requesting another."); + return; + } + } + + // subscribe(CoreSubscriber) may have requested a subscriber already. + if (!isRequested.getAndSet(true)) { + logger.info("Connection not requested, yet. Requesting one."); + upstream.request(1); + } else { + logger.info("Retried connection already requested."); + } + } + + /** + * Represents a subscriber, waiting for an AMQP connection. + */ + private static final class ConnectionSubscriber + extends Operators.MonoSubscriber { + private final EventHubConnectionProcessor processor; + + private ConnectionSubscriber(CoreSubscriber actual, + EventHubConnectionProcessor processor) { + super(actual); + this.processor = processor; + } + + @Override + public void cancel() { + super.cancel(); + processor.subscribers.remove(this); + } + + @Override + public void onComplete() { + if (!isCancelled()) { + actual.onComplete(); + } + } + + @Override + public void onNext(EventHubAmqpConnection connection) { + if (!isCancelled()) { + super.complete(connection); + } + } + + @Override + public void onError(Throwable throwable) { + if (!isCancelled()) { + actual.onError(throwable); + } else { + Operators.onOperatorError(throwable, currentContext()); + } + } + } +} diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubReactorAmqpConnection.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubReactorAmqpConnection.java index 10cafdd474a63..4c0bf642661f0 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubReactorAmqpConnection.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/EventHubReactorAmqpConnection.java @@ -4,18 +4,27 @@ package com.azure.messaging.eventhubs.implementation; import com.azure.core.amqp.AmqpRetryOptions; +import com.azure.core.amqp.AmqpRetryPolicy; import com.azure.core.amqp.AmqpSession; +import com.azure.core.amqp.implementation.AmqpReceiveLink; +import com.azure.core.amqp.implementation.AmqpSendLink; import com.azure.core.amqp.implementation.ConnectionOptions; import com.azure.core.amqp.implementation.MessageSerializer; import com.azure.core.amqp.implementation.ReactorConnection; import com.azure.core.amqp.implementation.ReactorHandlerProvider; import com.azure.core.amqp.implementation.ReactorProvider; +import com.azure.core.amqp.implementation.RetryUtil; import com.azure.core.amqp.implementation.TokenManagerProvider; import com.azure.core.amqp.implementation.handler.SessionHandler; +import com.azure.core.util.logging.ClientLogger; +import com.azure.messaging.eventhubs.models.EventPosition; +import com.azure.messaging.eventhubs.models.ReceiveOptions; import org.apache.qpid.proton.engine.BaseHandler; import org.apache.qpid.proton.engine.Session; import reactor.core.publisher.Mono; +import java.util.concurrent.ConcurrentHashMap; + /** * A proton-j AMQP connection to an Azure Event Hub instance. Adds additional support for management operations. */ @@ -24,6 +33,12 @@ public class EventHubReactorAmqpConnection extends ReactorConnection implements private static final String MANAGEMENT_LINK_NAME = "mgmt"; private static final String MANAGEMENT_ADDRESS = "$management"; + private final ClientLogger logger = new ClientLogger(EventHubReactorAmqpConnection.class); + /** + * Keeps track of the opened send links. Links are key'd by their entityPath. The send link for allowing the service + * load balance messages is the eventHubName. + */ + private final ConcurrentHashMap sendLinks = new ConcurrentHashMap<>(); private final Mono managementChannelMono; private final ReactorProvider reactorProvider; private final ReactorHandlerProvider handlerProvider; @@ -42,10 +57,11 @@ public class EventHubReactorAmqpConnection extends ReactorConnection implements * @param messageSerializer Serializes and deserializes proton-j messages. */ public EventHubReactorAmqpConnection(String connectionId, ConnectionOptions connectionOptions, - ReactorProvider reactorProvider, ReactorHandlerProvider handlerProvider, - TokenManagerProvider tokenManagerProvider, MessageSerializer messageSerializer) { + ReactorProvider reactorProvider, ReactorHandlerProvider handlerProvider, + TokenManagerProvider tokenManagerProvider, MessageSerializer messageSerializer, String product, + String clientVersion) { super(connectionId, connectionOptions, reactorProvider, handlerProvider, tokenManagerProvider, - messageSerializer); + messageSerializer, product, clientVersion); this.reactorProvider = reactorProvider; this.handlerProvider = handlerProvider; this.tokenManagerProvider = tokenManagerProvider; @@ -72,4 +88,62 @@ protected AmqpSession createSession(String sessionName, Session session, Session return new EventHubReactorSession(session, handler, sessionName, reactorProvider, handlerProvider, getClaimsBasedSecurityNode(), tokenManagerProvider, retryOptions.getTryTimeout(), messageSerializer); } + + /** + * Creates or gets a send link. The same link is returned if there is an existing send link with the same {@code + * linkName}. Otherwise, a new link is created and returned. + * + * @param linkName The name of the link. + * @param entityPath The remote address to connect to for the message broker. + * @param retryOptions Options to use when creating the link. + * @return A new or existing send link that is connected to the given {@code entityPath}. + */ + @Override + public Mono createSendLink(String linkName, String entityPath, AmqpRetryOptions retryOptions) { + final AmqpSendLink openLink = sendLinks.get(entityPath); + + if (openLink != null) { + return Mono.just(openLink); + } + + return createSession(entityPath).flatMap(session -> { + logger.info("Creating producer for {}", entityPath); + final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(retryOptions); + + return session.createProducer(linkName, entityPath, retryOptions.getTryTimeout(), retryPolicy) + .cast(AmqpSendLink.class); + }).map(link -> sendLinks.computeIfAbsent(entityPath, unusedKey -> link)); + } + + /** + * Creates or gets an existing receive link. The same link is returned if there is an existing receive link with the + * same {@code linkName}. Otherwise, a new link is created and returned. + * + * @param linkName The name of the link. + * @param entityPath The remote address to connect to for the message broker. + * @param eventPosition Position to set the receive link to. + * @param options Consumer options to use when creating the link. + * @return A new or existing receive link that is connected to the given {@code entityPath}. + */ + @Override + public Mono createReceiveLink(String linkName, String entityPath, EventPosition eventPosition, + ReceiveOptions options) { + return createSession(entityPath).cast(EventHubSession.class) + .flatMap(session -> { + logger.verbose("Creating consumer for path: {}", entityPath); + final AmqpRetryPolicy retryPolicy = RetryUtil.getRetryPolicy(retryOptions); + + return session.createConsumer(linkName, entityPath, retryOptions.getTryTimeout(), retryPolicy, + eventPosition, options); + }); + } + + @Override + public void close() { + logger.info("Disposing of connection."); + sendLinks.forEach((key, value) -> value.close()); + sendLinks.clear(); + + super.close(); + } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/PartitionProcessorException.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/PartitionProcessorException.java new file mode 100644 index 0000000000000..2b2f13b00fb0b --- /dev/null +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/implementation/PartitionProcessorException.java @@ -0,0 +1,30 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventhubs.implementation; + +import com.azure.core.exception.AzureException; + +/** + * Exception to wrap around the exception that was thrown from user's process event callback. + */ +public class PartitionProcessorException extends AzureException { + private static final long serialVersionUID = 6842246662817290407L; + + /** + * Creates and instance of this exception with the given message. + * @param message The error message. + */ + public PartitionProcessorException(String message) { + super(message); + } + + /** + * Creates an instance of this exception with the given message and cause. + * @param message The error message. + * @param cause The underlying cause for this exception. + */ + public PartitionProcessorException(String message, Throwable cause) { + super(message, cause); + } +} diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/models/InitializationContext.java b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/models/InitializationContext.java index b7171ed26634c..91ea189e1050e 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/models/InitializationContext.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/java/com/azure/messaging/eventhubs/models/InitializationContext.java @@ -3,7 +3,6 @@ package com.azure.messaging.eventhubs.models; -import com.azure.messaging.eventhubs.CheckpointStore; import com.azure.messaging.eventhubs.EventProcessorClient; import com.azure.messaging.eventhubs.EventProcessorClientBuilder; import java.util.Objects; @@ -17,19 +16,15 @@ public class InitializationContext { private final PartitionContext partitionContext; - private EventPosition initialPosition; /** * Creates an instance of InitializationContext for the partition provided in the {@link PartitionContext}. * * @param partitionContext The partition information for which the event processing is going to start. - * @param initialPosition The default initial event position from which the processing will start in the absence of - * a checkpoint in {@link CheckpointStore}. * @throws NullPointerException if {@code partitionContext} or {@code initialPosition}is {@code null}. */ - public InitializationContext(final PartitionContext partitionContext, final EventPosition initialPosition) { + public InitializationContext(final PartitionContext partitionContext) { this.partitionContext = Objects.requireNonNull(partitionContext, "'partitionContext' cannot be null"); - this.initialPosition = Objects.requireNonNull(initialPosition, "'initialPosition' cannot be null"); } /** @@ -40,27 +35,4 @@ public InitializationContext(final PartitionContext partitionContext, final Even public PartitionContext getPartitionContext() { return partitionContext; } - - /** - * Returns the default initial event position from which the processing will start in the absence of a checkpoint in - * {@link CheckpointStore}. - * - * @return The default initial event position from which the processing will start in the absence of a checkpoint in - * {@link CheckpointStore}. - */ - public EventPosition getInitialPosition() { - return initialPosition; - } - - /** - * If a different initial position is desirable for this partition, setting the initial position will start the - * event processing from this position. Note that the checkpoint in {@link CheckpointStore} is given the highest - * priority and if there's a checkpoint in the store, that will be used regardless of what is set in this method. - * - * @param initialPosition The initial event position to start the event processing from. - * @throws NullPointerException if {@code initialPosition} is {@code null}. - */ - public void setInitialPosition(final EventPosition initialPosition) { - this.initialPosition = Objects.requireNonNull(initialPosition, "'initialPosition' cannot be null"); - } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/main/resources/azure-messaging-eventhubs.properties b/sdk/eventhubs/azure-messaging-eventhubs/src/main/resources/azure-messaging-eventhubs.properties new file mode 100644 index 0000000000000..ca812989b4f27 --- /dev/null +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/main/resources/azure-messaging-eventhubs.properties @@ -0,0 +1,2 @@ +name=${project.artifactId} +version=${project.version} diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventProcessorClientAggregateEventsSample.java b/sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventProcessorClientAggregateEventsSample.java index 30579d62796e2..c7d6a6e5e0992 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventProcessorClientAggregateEventsSample.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/samples/java/com/azure/messaging/eventhubs/EventProcessorClientAggregateEventsSample.java @@ -98,7 +98,7 @@ public static void main(String[] args) throws Exception { */ private static Mono generateEvents(AtomicBoolean isRunning) { final Logger logger = LoggerFactory.getLogger("Producer"); - final Scheduler scheduler = Schedulers.newElastic("produce"); + final Scheduler scheduler = Schedulers.elastic(); final Duration operationTimeout = Duration.ofSeconds(5); final String[] machineIds = new String[]{"2A", "9B", "6C"}; final Random random = new Random(); @@ -129,10 +129,11 @@ private static Mono generateEvents(AtomicBoolean isRunning) { return client.send(batch); }).block(operationTimeout); } - }).doFinally(signal -> { - logger.info("Disposing of producer."); - client.close(); - }).subscribeOn(scheduler); + }).subscribeOn(scheduler) + .doFinally(signal -> { + logger.info("Disposing of producer."); + client.close(); + }); } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConnectionTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConnectionTest.java deleted file mode 100644 index cb21b35b7b4d6..0000000000000 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConnectionTest.java +++ /dev/null @@ -1,151 +0,0 @@ -// Copyright (c) Microsoft Corporation. All rights reserved. -// Licensed under the MIT License. - -package com.azure.messaging.eventhubs; - -import com.azure.core.amqp.AmqpRetryMode; -import com.azure.core.amqp.AmqpRetryOptions; -import com.azure.core.amqp.AmqpTransportType; -import com.azure.core.amqp.ExponentialAmqpRetryPolicy; -import com.azure.core.amqp.FixedAmqpRetryPolicy; -import com.azure.core.amqp.ProxyOptions; -import com.azure.core.amqp.implementation.AmqpReceiveLink; -import com.azure.core.amqp.implementation.AmqpSendLink; -import com.azure.core.amqp.implementation.CbsAuthorizationType; -import com.azure.core.amqp.implementation.ConnectionOptions; -import com.azure.core.credential.TokenCredential; -import com.azure.messaging.eventhubs.implementation.EventHubAmqpConnection; -import com.azure.messaging.eventhubs.implementation.EventHubManagementNode; -import com.azure.messaging.eventhubs.implementation.EventHubSession; -import com.azure.messaging.eventhubs.models.EventPosition; -import com.azure.messaging.eventhubs.models.ReceiveOptions; -import org.junit.jupiter.api.AfterEach; -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.Mono; -import reactor.core.scheduler.Schedulers; -import reactor.test.StepVerifier; - -import java.io.IOException; -import java.time.Duration; - -import static org.mockito.ArgumentMatchers.argThat; -import static org.mockito.ArgumentMatchers.eq; -import static org.mockito.Mockito.mock; -import static org.mockito.Mockito.times; -import static org.mockito.Mockito.verify; -import static org.mockito.Mockito.when; - -public class EventHubConnectionTest { - private static final Duration TIMEOUT = Duration.ofSeconds(2); - private static final String HOST_NAME = "Some-host-name"; - private final AmqpRetryOptions retryOptions = new AmqpRetryOptions() - .setTryTimeout(Duration.ofSeconds(5)) - .setMaxRetries(0); - - @Mock - private EventHubAmqpConnection connection; - @Mock - private EventHubSession session; - @Mock - private TokenCredential tokenCredential; - - private EventHubConnection provider; - - @BeforeEach - public void setup() { - MockitoAnnotations.initMocks(this); - ConnectionOptions connectionOptions = new ConnectionOptions(HOST_NAME, "event-hub-path", tokenCredential, - CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP_WEB_SOCKETS, retryOptions, - ProxyOptions.SYSTEM_DEFAULTS, Schedulers.parallel()); - provider = new EventHubConnection(Mono.just(connection), connectionOptions); - } - - @Test - public void getManagementNode() { - // Arrange - EventHubManagementNode managementNode = mock(EventHubManagementNode.class); - when(connection.getManagementNode()).thenReturn(Mono.just(managementNode)); - - // Act & Assert - StepVerifier.create(provider.getManagementNode()) - .expectNext(managementNode) - .expectComplete() - .verify(TIMEOUT); - } - - @Test - public void getSendLink() { - // Arrange - final Duration timeout = Duration.ofSeconds(4); - final AmqpSendLink sendLink = mock(AmqpSendLink.class); - final AmqpRetryOptions options = new AmqpRetryOptions() - .setTryTimeout(timeout) - .setMaxRetries(2) - .setMode(AmqpRetryMode.FIXED); - - final String linkName = "some-link-name"; - final String entityPath = "some-entity-path"; - when(connection.createSession(entityPath)).thenReturn(Mono.just(session)); - when(session.createProducer(eq(linkName), eq(entityPath), eq(timeout), - argThat(matcher -> options.getMaxRetries() == matcher.getMaxRetries() - && matcher instanceof FixedAmqpRetryPolicy))) - .thenReturn(Mono.just(sendLink)); - - // Act & Assert - StepVerifier.create(provider.createSendLink(linkName, entityPath, options)) - .expectNext(sendLink) - .verifyComplete(); - } - - @Test - public void getReceiveLink() { - // Arrange - final AmqpReceiveLink receiveLink = mock(AmqpReceiveLink.class); - final ReceiveOptions options = new ReceiveOptions(); - - final EventPosition position = EventPosition.fromOffset(10L); - final String linkName = "some-link-name"; - final String entityPath = "some-entity-path"; - - when(connection.createSession(entityPath)).thenReturn(Mono.just(session)); - when(session.createConsumer( - eq(linkName), eq(entityPath), eq(retryOptions.getTryTimeout()), - argThat(matcher -> retryOptions.getMaxRetries() == matcher.getMaxRetries() - && matcher instanceof ExponentialAmqpRetryPolicy), - eq(position), eq(options))) - .thenReturn(Mono.just(receiveLink)); - - // Act & Assert - StepVerifier.create(provider.createReceiveLink(linkName, entityPath, position, options)) - .expectNext(receiveLink) - .verifyComplete(); - } - - @Test - public void disposesOnce() throws IOException { - // Arrange - final EventHubManagementNode node = mock(EventHubManagementNode.class); - when(connection.getManagementNode()).thenReturn(Mono.just(node)); - - // Force us to evaluate the connection Mono - provider.getManagementNode().block(); - - // Act - provider.close(); - - // This should not call connection.close() a second time. The connection has already been disposed. - provider.close(); - - // Assert - verify(connection, times(1)).close(); - } - - @AfterEach - public void teardown() { - Mockito.framework().clearInlineMocks(); - } -} diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientIntegrationTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientIntegrationTest.java index e1e6eaa197741..50f742d21fc03 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientIntegrationTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientIntegrationTest.java @@ -386,7 +386,7 @@ public void canReceive() { } finally { isActive.set(false); producerEvents.dispose(); - consumer.close(); + dispose(producer, consumer); } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientTest.java index 7aa341a6d98b2..cd1010f909dea 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerAsyncClientTest.java @@ -14,8 +14,8 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.implementation.EventHubAmqpConnection; +import com.azure.messaging.eventhubs.implementation.EventHubConnectionProcessor; import com.azure.messaging.eventhubs.implementation.EventHubManagementNode; -import com.azure.messaging.eventhubs.implementation.EventHubSession; import com.azure.messaging.eventhubs.models.EventPosition; import com.azure.messaging.eventhubs.models.LastEnqueuedEventProperties; import com.azure.messaging.eventhubs.models.PartitionEvent; @@ -57,6 +57,7 @@ import static com.azure.messaging.eventhubs.TestUtils.isMatchingEvent; import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.Mockito.atLeastOnce; import static org.mockito.Mockito.mock; @@ -68,7 +69,7 @@ /** * Unit tests to verify functionality of {@link EventHubConsumerAsyncClient}. */ -public class EventHubConsumerAsyncClientTest { +class EventHubConsumerAsyncClientTest { static final String PARTITION_ID_HEADER = "partition-id-sent"; private static final Duration TIMEOUT = Duration.ofSeconds(30); @@ -81,8 +82,10 @@ public class EventHubConsumerAsyncClientTest { private static final String PARTITION_ID = "a-partition-id"; private final ClientLogger logger = new ClientLogger(EventHubConsumerAsyncClientTest.class); + private final AmqpRetryOptions retryOptions = new AmqpRetryOptions().setMaxRetries(2); private final String messageTrackingUUID = UUID.randomUUID().toString(); private final DirectProcessor endpointProcessor = DirectProcessor.create(); + private final FluxSink endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private final DirectProcessor messageProcessor = DirectProcessor.create(); @Mock @@ -90,51 +93,53 @@ public class EventHubConsumerAsyncClientTest { @Mock private EventHubAmqpConnection connection; @Mock - private EventHubSession session; - @Mock private TokenCredential tokenCredential; @Captor private ArgumentCaptor> creditSupplier; - private EventHubConnection eventHubConnection; private MessageSerializer messageSerializer = new EventHubMessageSerializer(); private EventHubConsumerAsyncClient consumer; - private ConnectionOptions connectionOptions; + private EventHubConnectionProcessor connectionProcessor; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); when(amqpReceiveLink.receive()).thenReturn(messageProcessor); when(amqpReceiveLink.getEndpointStates()).thenReturn(endpointProcessor); - connectionOptions = new ConnectionOptions(HOSTNAME, "event-hub-path", tokenCredential, + ConnectionOptions connectionOptions = new ConnectionOptions(HOSTNAME, "event-hub-path", tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP_WEB_SOCKETS, new AmqpRetryOptions(), ProxyOptions.SYSTEM_DEFAULTS, Schedulers.parallel()); - eventHubConnection = new EventHubConnection(Mono.just(connection), connectionOptions); - when(connection.createSession(any())).thenReturn(Mono.just(session)); - when(session.createConsumer(any(), argThat(name -> name.endsWith(PARTITION_ID)), any(), any(), any(), any())) - .thenReturn(Mono.just(amqpReceiveLink)); - consumer = new EventHubConsumerAsyncClient(HOSTNAME, EVENT_HUB_NAME, eventHubConnection, messageSerializer, + when(connection.getEndpointStates()).thenReturn(endpointProcessor); + endpointSink.next(AmqpEndpointState.ACTIVE); + + when(connection.createReceiveLink(anyString(), argThat(name -> name.endsWith(PARTITION_ID)), + any(EventPosition.class), any(ReceiveOptions.class))).thenReturn(Mono.just(amqpReceiveLink)); + connectionProcessor = Flux.create(sink -> sink.next(connection)) + .subscribeWith(new EventHubConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), + connectionOptions.getEntityPath(), connectionOptions.getRetry())); + + consumer = new EventHubConsumerAsyncClient(HOSTNAME, EVENT_HUB_NAME, connectionProcessor, messageSerializer, CONSUMER_GROUP, PREFETCH, false); } @AfterEach - public void teardown() { + void teardown() { Mockito.framework().clearInlineMocks(); consumer.close(); } /** - * Verify that by default, lastEnqueuedInformation is null if - * {@link ReceiveOptions#getTrackLastEnqueuedEventProperties()} is not set. + * Verify that by default, lastEnqueuedInformation is null if {@link ReceiveOptions#getTrackLastEnqueuedEventProperties()} + * is not set. */ @Test - public void lastEnqueuedEventInformationIsNull() { + void lastEnqueuedEventInformationIsNull() { final EventHubConsumerAsyncClient runtimeConsumer = new EventHubConsumerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - eventHubConnection, messageSerializer, CONSUMER_GROUP, DEFAULT_PREFETCH_COUNT, false); + connectionProcessor, messageSerializer, CONSUMER_GROUP, DEFAULT_PREFETCH_COUNT, false); final int numberOfEvents = 10; when(amqpReceiveLink.getCredits()).thenReturn(numberOfEvents); final int numberToReceive = 3; @@ -152,10 +157,10 @@ public void lastEnqueuedEventInformationIsNull() { * Verify that the default information is set and is null because no information has been received. */ @Test - public void lastEnqueuedEventInformationCreated() { + void lastEnqueuedEventInformationCreated() { // Arrange final EventHubConsumerAsyncClient runtimeConsumer = new EventHubConsumerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - eventHubConnection, messageSerializer, CONSUMER_GROUP, DEFAULT_PREFETCH_COUNT, false); + connectionProcessor, messageSerializer, CONSUMER_GROUP, DEFAULT_PREFETCH_COUNT, false); final int numberOfEvents = 10; final ReceiveOptions receiveOptions = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); when(amqpReceiveLink.getCredits()).thenReturn(numberOfEvents); @@ -180,7 +185,7 @@ public void lastEnqueuedEventInformationCreated() { * prefetch value. */ @Test - public void receivesNumberOfEvents() { + void receivesNumberOfEvents() { // Arrange final int numberOfEvents = 10; @@ -198,23 +203,24 @@ public void receivesNumberOfEvents() { */ @SuppressWarnings("unchecked") @Test - public void returnsNewListener() { + void returnsNewListener() { // Arrange final int numberOfEvents = 10; EventHubAmqpConnection connection1 = mock(EventHubAmqpConnection.class); - EventHubConnection eventHubConnection = new EventHubConnection(Mono.fromCallable(() -> connection1), - connectionOptions); + EventHubConnectionProcessor eventHubConnection = Flux.create(sink -> sink.next(connection1)) + .subscribeWith(new EventHubConnectionProcessor(HOSTNAME, EVENT_HUB_NAME, retryOptions)); + + when(connection1.getEndpointStates()).thenReturn(endpointProcessor); + endpointSink.next(AmqpEndpointState.ACTIVE); EmitterProcessor processor2 = EmitterProcessor.create(); FluxSink processor2sink = processor2.sink(); AmqpReceiveLink link2 = mock(AmqpReceiveLink.class); - EventHubSession session2 = mock(EventHubSession.class); EmitterProcessor processor3 = EmitterProcessor.create(); FluxSink processor3sink = processor3.sink(); AmqpReceiveLink link3 = mock(AmqpReceiveLink.class); - EventHubSession session3 = mock(EventHubSession.class); when(link2.receive()).thenReturn(processor2); when(link2.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); @@ -224,11 +230,8 @@ public void returnsNewListener() { when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link3.getCredits()).thenReturn(numberOfEvents); - when(connection1.createSession(any())).thenReturn(Mono.just(session2), Mono.just(session3)); - when(session2.createConsumer(any(), argThat(name -> name.endsWith(PARTITION_ID)), any(), any(), any(), any())) - .thenReturn(Mono.just(link2)); - when(session3.createConsumer(any(), argThat(name -> name.endsWith(PARTITION_ID)), any(), any(), any(), any())) - .thenReturn(Mono.just(link3)); + when(connection1.createReceiveLink(any(), argThat(arg -> arg.endsWith(PARTITION_ID)), any(EventPosition.class), + any(ReceiveOptions.class))).thenReturn(Mono.just(link2), Mono.just(link3)); EventHubConsumerAsyncClient asyncClient = new EventHubConsumerAsyncClient(HOSTNAME, EVENT_HUB_NAME, eventHubConnection, messageSerializer, CONSUMER_GROUP, PREFETCH, false); @@ -254,7 +257,7 @@ public void returnsNewListener() { * Verify that receive can have multiple subscribers. */ @Test - public void canHaveMultipleSubscribers() throws InterruptedException { + void canHaveMultipleSubscribers() throws InterruptedException { // Arrange final int numberOfEvents = 7; final CountDownLatch firstConsumerCountDown = new CountDownLatch(numberOfEvents); @@ -292,7 +295,7 @@ public void canHaveMultipleSubscribers() throws InterruptedException { * Verifies that we can limit the number of deliveries added on the link at a given time. */ @Test - public void canLimitRequestsBackpressure() throws InterruptedException { + void canLimitRequestsBackpressure() throws InterruptedException { // Arrange final int numberOfEvents = 20; final int backpressureRequest = 2; @@ -334,7 +337,7 @@ protected void hookOnNext(PartitionEvent value) { * Verifies that if we have limited the request, the number of credits added is the same as that limit. */ @Test - public void returnsCorrectCreditRequest() throws InterruptedException { + void returnsCorrectCreditRequest() throws InterruptedException { // Arrange final int numberOfEvents = 20; final int backpressureRequest = 2; @@ -376,7 +379,7 @@ protected void hookOnNext(PartitionEvent value) { * Verify that the correct number of credits are returned when the link is empty, and there are subscribers. */ @Test - public void suppliesCreditsWhenSubscribers() { + void suppliesCreditsWhenSubscribers() { // Arrange final int backPressure = 8; @@ -407,7 +410,7 @@ public void suppliesCreditsWhenSubscribers() { * Verify that 0 credits are returned when there are no subscribers for this link anymore. */ @Test - public void suppliesNoCreditsWhenNoSubscribers() { + void suppliesNoCreditsWhenNoSubscribers() { // Arrange final int backPressure = 8; @@ -437,7 +440,7 @@ public void suppliesNoCreditsWhenNoSubscribers() { * Verifies that the consumer closes and completes any listeners on a shutdown signal. */ @Test - public void listensToShutdownSignals() throws InterruptedException { + void listensToShutdownSignals() throws InterruptedException { // Arrange final int numberOfEvents = 7; final CountDownLatch shutdownReceived = new CountDownLatch(3); @@ -487,7 +490,7 @@ public void listensToShutdownSignals() throws InterruptedException { } @Test - public void setsCorrectProperties() { + void setsCorrectProperties() { // Act EventHubConsumerAsyncClient consumer = new EventHubClientBuilder() .connectionString("Endpoint=sb://doesnotexist.servicebus.windows.net/;SharedAccessKeyName=doesnotexist;SharedAccessKey=dGhpcyBpcyBub3QgYSB2YWxpZCBrZXkgLi4uLi4uLi4=;EntityPath=dummy-event-hub") @@ -500,17 +503,23 @@ public void setsCorrectProperties() { } @Test - public void receivesMultiplePartitions() { + void receivesMultiplePartitions() { + // Arrange int numberOfEvents = 10; when(amqpReceiveLink.getCredits()).thenReturn(numberOfEvents); EventHubAmqpConnection connection1 = mock(EventHubAmqpConnection.class); - EventHubConnection eventHubConnection = new EventHubConnection(Mono.fromCallable(() -> connection1), - connectionOptions); + EventHubConnectionProcessor eventHubConnection = Flux.create(sink -> sink.next(connection1)) + .subscribeWith(new EventHubConnectionProcessor(HOSTNAME, EVENT_HUB_NAME, retryOptions)); + + when(connection1.getEndpointStates()).thenReturn(endpointProcessor); + endpointSink.next(AmqpEndpointState.ACTIVE); String id2 = "partition-2"; String id3 = "partition-3"; String[] partitions = new String[]{PARTITION_ID, id2, id3}; + + // Set-up management node returns. EventHubManagementNode managementNode = mock(EventHubManagementNode.class); when(connection1.getManagementNode()).thenReturn(Mono.just(managementNode)); when(managementNode.getEventHubProperties()) @@ -522,12 +531,10 @@ public void receivesMultiplePartitions() { EmitterProcessor processor2 = EmitterProcessor.create(); FluxSink processor2sink = processor2.sink(); AmqpReceiveLink link2 = mock(AmqpReceiveLink.class); - EventHubSession session2 = mock(EventHubSession.class); EmitterProcessor processor3 = EmitterProcessor.create(); FluxSink processor3sink = processor3.sink(); AmqpReceiveLink link3 = mock(AmqpReceiveLink.class); - EventHubSession session3 = mock(EventHubSession.class); when(link2.receive()).thenReturn(processor2); when(link2.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); @@ -537,24 +544,19 @@ public void receivesMultiplePartitions() { when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link3.getCredits()).thenReturn(numberOfEvents); - when(connection1.createSession(any())).thenAnswer(invocation -> { - String name = invocation.getArgument(0); - - if (name.endsWith(PARTITION_ID)) { - return Mono.just(session); - } else if (name.endsWith(id2)) { - return Mono.just(session2); - } else if (name.endsWith(id3)) { - return Mono.just(session3); - } else { - return Mono.error(new IllegalArgumentException("Unknown session: " + name)); - } - }); - when(session2.createConsumer(any(), argThat(name -> name.endsWith(id2)), any(), any(), any(), any())) - .thenReturn(Mono.just(link2)); - - when(session3.createConsumer(any(), argThat(name -> name.endsWith(id3)), any(), any(), any(), any())) - .thenReturn(Mono.just(link3)); + when(connection1.createReceiveLink(any(), anyString(), any(EventPosition.class), any(ReceiveOptions.class))) + .thenAnswer(mock -> { + String name = mock.getArgument(1); + if (name.endsWith(PARTITION_ID)) { + return Mono.just(amqpReceiveLink); + } else if (name.endsWith(id2)) { + return Mono.just(link2); + } else if (name.endsWith(id3)) { + return Mono.just(link3); + } else { + return Mono.error(new IllegalArgumentException("Unknown entityPath: " + name)); + } + }); // Act & Assert StepVerifier.create(asyncClient.receive(true).filter(e -> isMatchingEvent(e, messageTrackingUUID))) @@ -573,18 +575,24 @@ public void receivesMultiplePartitions() { * Verifies that even if one link closes, it still continues to receive. */ @Test - public void receivesMultiplePartitionsWhenOneCloses() { + void receivesMultiplePartitionsWhenOneCloses() { + // Arrange int numberOfEvents = 10; when(amqpReceiveLink.getCredits()).thenReturn(numberOfEvents); final FluxSink processor1sink = messageProcessor.sink(); EventHubAmqpConnection connection1 = mock(EventHubAmqpConnection.class); - EventHubConnection eventHubConnection = new EventHubConnection(Mono.fromCallable(() -> connection1), - connectionOptions); + EventHubConnectionProcessor eventHubConnection = Flux.create(sink -> sink.next(connection1)) + .subscribeWith(new EventHubConnectionProcessor(HOSTNAME, EVENT_HUB_NAME, retryOptions)); + + when(connection1.getEndpointStates()).thenReturn(endpointProcessor); + endpointSink.next(AmqpEndpointState.ACTIVE); String id2 = "partition-2"; String id3 = "partition-3"; String[] partitions = new String[]{PARTITION_ID, id2, id3}; + + // Set-up management node returns. EventHubManagementNode managementNode = mock(EventHubManagementNode.class); when(connection1.getManagementNode()).thenReturn(Mono.just(managementNode)); when(managementNode.getEventHubProperties()) @@ -596,43 +604,32 @@ public void receivesMultiplePartitionsWhenOneCloses() { EmitterProcessor processor2 = EmitterProcessor.create(); FluxSink processor2sink = processor2.sink(); AmqpReceiveLink link2 = mock(AmqpReceiveLink.class); - EventHubSession session2 = mock(EventHubSession.class); EmitterProcessor processor3 = EmitterProcessor.create(); FluxSink processor3sink = processor3.sink(); AmqpReceiveLink link3 = mock(AmqpReceiveLink.class); - EventHubSession session3 = mock(EventHubSession.class); when(link2.receive()).thenReturn(processor2); - when(link2.getEndpointStates()).thenReturn(Flux.create(sink -> { - sink.next(AmqpEndpointState.ACTIVE); - })); + when(link2.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link2.getCredits()).thenReturn(numberOfEvents); when(link3.receive()).thenReturn(processor3); - when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> { - sink.next(AmqpEndpointState.ACTIVE); - })); + when(link3.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); when(link3.getCredits()).thenReturn(numberOfEvents); - when(connection1.createSession(any())).thenAnswer(invocation -> { - String name = invocation.getArgument(0); - - if (name.endsWith(PARTITION_ID)) { - return Mono.just(session); - } else if (name.endsWith(id2)) { - return Mono.just(session2); - } else if (name.endsWith(id3)) { - return Mono.just(session3); - } else { - return Mono.error(new IllegalArgumentException("Unknown session: " + name)); - } - }); - when(session2.createConsumer(any(), argThat(name -> name.endsWith(id2)), any(), any(), any(), any())) - .thenReturn(Mono.just(link2)); - - when(session3.createConsumer(any(), argThat(name -> name.endsWith(id3)), any(), any(), any(), any())) - .thenReturn(Mono.just(link3)); + when(connection1.createReceiveLink(any(), anyString(), any(EventPosition.class), any(ReceiveOptions.class))) + .thenAnswer(mock -> { + String name = mock.getArgument(1); + if (name.endsWith(PARTITION_ID)) { + return Mono.just(amqpReceiveLink); + } else if (name.endsWith(id2)) { + return Mono.just(link2); + } else if (name.endsWith(id3)) { + return Mono.just(link3); + } else { + return Mono.error(new IllegalArgumentException("Unknown session: " + name)); + } + }); // Act & Assert StepVerifier.create(asyncClient.receive(true).filter(e -> isMatchingEvent(e, messageTrackingUUID))) @@ -654,26 +651,29 @@ public void receivesMultiplePartitionsWhenOneCloses() { * Verifies that when we have a shared connection, the consumer does not close that connection. */ @Test - public void doesNotCloseSharedConnection() { + void doesNotCloseSharedConnection() { // Arrange - EventHubConnection hubConnection = mock(EventHubConnection.class); + EventHubAmqpConnection connection1 = mock(EventHubAmqpConnection.class); + EventHubConnectionProcessor eventHubConnection = Flux.create(sink -> sink.next(connection1)) + .subscribeWith(new EventHubConnectionProcessor(HOSTNAME, EVENT_HUB_NAME, retryOptions)); EventHubConsumerAsyncClient sharedConsumer = new EventHubConsumerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - hubConnection, messageSerializer, CONSUMER_GROUP, PREFETCH, true); + eventHubConnection, messageSerializer, CONSUMER_GROUP, PREFETCH, true); // Act sharedConsumer.close(); // Verify - verify(hubConnection, never()).close(); + Assertions.assertFalse(eventHubConnection.isDisposed()); + verify(connection1, never()).close(); } /** * Verifies that when we have a non-shared connection, the consumer closes that connection. */ @Test - public void closesDedicatedConnection() { + void closesDedicatedConnection() { // Arrange - EventHubConnection hubConnection = mock(EventHubConnection.class); + EventHubConnectionProcessor hubConnection = mock(EventHubConnectionProcessor.class); EventHubConsumerAsyncClient dedicatedConsumer = new EventHubConsumerAsyncClient(HOSTNAME, EVENT_HUB_NAME, hubConnection, messageSerializer, CONSUMER_GROUP, PREFETCH, false); @@ -681,7 +681,7 @@ public void closesDedicatedConnection() { dedicatedConsumer.close(); // Verify - verify(hubConnection, times(1)).close(); + verify(hubConnection, times(1)).dispose(); } private void assertPartition(String partitionId, PartitionEvent event) { diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientIntegrationTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientIntegrationTest.java index 1d1a40315df30..51d1050c89a74 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientIntegrationTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientIntegrationTest.java @@ -37,7 +37,6 @@ public class EventHubConsumerClientIntegrationTest extends IntegrationTestBase { private EventHubClient client; private EventHubConsumerClient consumer; - private EventHubConnection connection; private EventPosition startingPosition; // We use these values to keep track of the events we've pushed to the service and ensure the events we receive are @@ -71,7 +70,7 @@ protected void beforeTest() { @Override protected void afterTest() { - dispose(consumer, connection, client); + dispose(consumer, client); } /** diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientTest.java index 6940f7b8457ce..6128c8e5cd071 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubConsumerClientTest.java @@ -3,6 +3,7 @@ package com.azure.messaging.eventhubs; +import com.azure.core.amqp.AmqpEndpointState; import com.azure.core.amqp.AmqpRetryOptions; import com.azure.core.amqp.AmqpTransportType; import com.azure.core.amqp.ProxyOptions; @@ -13,7 +14,7 @@ import com.azure.core.credential.TokenCredential; import com.azure.core.util.IterableStream; import com.azure.messaging.eventhubs.implementation.EventHubAmqpConnection; -import com.azure.messaging.eventhubs.implementation.EventHubSession; +import com.azure.messaging.eventhubs.implementation.EventHubConnectionProcessor; import com.azure.messaging.eventhubs.models.EventPosition; import com.azure.messaging.eventhubs.models.LastEnqueuedEventProperties; import com.azure.messaging.eventhubs.models.PartitionEvent; @@ -27,6 +28,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.EmitterProcessor; import reactor.core.publisher.Flux; import reactor.core.publisher.FluxSink; @@ -71,6 +73,8 @@ public class EventHubConsumerClientTest { private final FluxSink sink = messageProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private final MessageSerializer messageSerializer = new EventHubMessageSerializer(); + private final DirectProcessor endpointProcessor = DirectProcessor.create(); + @Mock private AmqpReceiveLink amqpReceiveLink; @Mock @@ -78,13 +82,12 @@ public class EventHubConsumerClientTest { @Mock private EventHubAmqpConnection connection; - @Mock - private EventHubSession session; + @Mock private TokenCredential tokenCredential; private EventHubConsumerClient consumer; - private EventHubConnection linkProvider; + private EventHubConnectionProcessor connectionProcessor; private ConnectionOptions connectionOptions; private EventHubConsumerAsyncClient asyncConsumer; @@ -100,17 +103,19 @@ public void setup() { connectionOptions = new ConnectionOptions(HOSTNAME, "event-hub-path", tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP_WEB_SOCKETS, new AmqpRetryOptions(), ProxyOptions.SYSTEM_DEFAULTS, Schedulers.parallel()); - linkProvider = new EventHubConnection(Mono.just(connection), connectionOptions); - when(connection.createSession(argThat(name -> name.endsWith(PARTITION_ID)))) - .thenReturn(Mono.fromCallable(() -> session)); - when(session.createConsumer(any(), argThat(name -> name.endsWith(PARTITION_ID)), any(), any(), any(), any())) + connectionProcessor = Flux.create(sink -> sink.next(connection)) + .subscribeWith(new EventHubConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), + connectionOptions.getEntityPath(), connectionOptions.getRetry())); + + when(connection.getEndpointStates()).thenReturn(endpointProcessor); + when(connection.createReceiveLink(any(), argThat(name -> name.endsWith(PARTITION_ID)), any(EventPosition.class), any(ReceiveOptions.class))) .thenReturn(Mono.just(amqpReceiveLink), Mono.fromCallable(() -> { System.out.println("Returning second link"); return amqpReceiveLink2; })); asyncConsumer = new EventHubConsumerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - linkProvider, messageSerializer, CONSUMER_GROUP, PREFETCH, false); + connectionProcessor, messageSerializer, CONSUMER_GROUP, PREFETCH, false); consumer = new EventHubConsumerClient(asyncConsumer, Duration.ofSeconds(10)); } @@ -133,7 +138,7 @@ public static void dispose() { public void lastEnqueuedEventInformationIsNull() { // Arrange final EventHubConsumerAsyncClient runtimeConsumer = new EventHubConsumerAsyncClient( - HOSTNAME, EVENT_HUB_NAME, linkProvider, messageSerializer, CONSUMER_GROUP, + HOSTNAME, EVENT_HUB_NAME, connectionProcessor, messageSerializer, CONSUMER_GROUP, PREFETCH, false); final EventHubConsumerClient consumer = new EventHubConsumerClient(runtimeConsumer, Duration.ofSeconds(5)); final int numberOfEvents = 10; @@ -161,7 +166,7 @@ public void lastEnqueuedEventInformationCreated() { // Arrange final ReceiveOptions options = new ReceiveOptions().setTrackLastEnqueuedEventProperties(true); final EventHubConsumerAsyncClient runtimeConsumer = new EventHubConsumerAsyncClient( - HOSTNAME, EVENT_HUB_NAME, linkProvider, messageSerializer, CONSUMER_GROUP, PREFETCH, false); + HOSTNAME, EVENT_HUB_NAME, connectionProcessor, messageSerializer, CONSUMER_GROUP, PREFETCH, false); final EventHubConsumerClient consumer = new EventHubConsumerClient(runtimeConsumer, Duration.ofSeconds(5)); final int numberOfEvents = 10; 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 de95c04f17e96..39514947940e5 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 @@ -3,17 +3,23 @@ package com.azure.messaging.eventhubs; +import com.azure.core.amqp.exception.AmqpException; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.models.CreateBatchOptions; import com.azure.messaging.eventhubs.models.SendOptions; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; import reactor.core.publisher.Flux; import reactor.core.publisher.Mono; import reactor.test.StepVerifier; +import java.time.Duration; +import java.time.Instant; import java.util.Arrays; import java.util.List; +import java.util.concurrent.TimeUnit; +import java.util.stream.IntStream; import static java.nio.charset.StandardCharsets.UTF_8; @@ -155,10 +161,12 @@ public void sendAllPartitions() { Assertions.assertNotNull(partitionIds); for (String partitionId : partitionIds) { - final EventDataBatch batch = producer.createBatch(new CreateBatchOptions().setPartitionId(partitionId)).block(TIMEOUT); + final EventDataBatch batch = + producer.createBatch(new CreateBatchOptions().setPartitionId(partitionId)).block(TIMEOUT); Assertions.assertNotNull(batch); - Assertions.assertTrue(batch.tryAdd(TestUtils.getEvent("event", "test guid", Integer.parseInt(partitionId)))); + Assertions.assertTrue(batch.tryAdd(TestUtils.getEvent("event", "test guid", + Integer.parseInt(partitionId)))); // Act & Assert StepVerifier.create(producer.send(batch)).expectComplete().verify(TIMEOUT); @@ -193,4 +201,36 @@ public void sendWithCredentials() { dispose(client); } } + + @Disabled("Testing long running operations and disconnections.") + @Test + void worksAfterReconnection() throws InterruptedException { + Flux.interval(Duration.ofSeconds(5)) + .flatMap(position -> producer.createBatch().flatMap(batch -> { + IntStream.range(0, 3).mapToObj(number -> new EventData("Position" + position + ": " + number)) + .forEach(event -> { + if (!batch.tryAdd(event)) { + logger.error("Could not add event. Size: {}. Max: {}. Content: {}", + batch.getSizeInBytes(), batch.getMaxSizeInBytes(), event.getBodyAsString()); + } + }); + + return producer.send(batch).thenReturn(Instant.now()); + })) + .onErrorContinue(error -> error instanceof AmqpException && ((AmqpException) error).isTransient(), + (error, value) -> { + System.out.println("Exception dropped: " + error.getMessage()); + }) + .subscribe(instant -> { + System.out.println("Sent batch at: " + instant); + }, error -> { + logger.error("Error sending batch: ", error); + }, () -> { + logger.info("Complete."); + }); + + System.out.println("Sleeping while performing work."); + TimeUnit.MINUTES.sleep(30); + System.out.println("Complete."); + } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClientTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClientTest.java index 198cb77c84078..946e759e2c2a9 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClientTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerAsyncClientTest.java @@ -3,11 +3,13 @@ package com.azure.messaging.eventhubs; +import com.azure.core.amqp.AmqpEndpointState; +import com.azure.core.amqp.AmqpRetryMode; import com.azure.core.amqp.AmqpRetryOptions; -import com.azure.core.amqp.AmqpSession; import com.azure.core.amqp.AmqpTransportType; import com.azure.core.amqp.ProxyOptions; import com.azure.core.amqp.exception.AmqpErrorCondition; +import com.azure.core.amqp.exception.AmqpErrorContext; import com.azure.core.amqp.exception.AmqpException; import com.azure.core.amqp.implementation.AmqpSendLink; import com.azure.core.amqp.implementation.CbsAuthorizationType; @@ -20,6 +22,7 @@ import com.azure.core.util.tracing.Tracer; import com.azure.messaging.eventhubs.implementation.ClientConstants; import com.azure.messaging.eventhubs.implementation.EventHubAmqpConnection; +import com.azure.messaging.eventhubs.implementation.EventHubConnectionProcessor; import com.azure.messaging.eventhubs.models.CreateBatchOptions; import com.azure.messaging.eventhubs.models.SendOptions; import org.apache.qpid.proton.amqp.messaging.Section; @@ -33,7 +36,9 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import reactor.core.publisher.DirectProcessor; import reactor.core.publisher.Flux; +import reactor.core.publisher.FluxSink; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import reactor.test.StepVerifier; @@ -41,6 +46,7 @@ import java.time.Duration; import java.util.Collections; import java.util.List; +import java.util.concurrent.atomic.AtomicInteger; import static com.azure.core.util.tracing.Tracer.DIAGNOSTIC_ID_KEY; import static com.azure.core.util.tracing.Tracer.PARENT_SPAN_KEY; @@ -49,6 +55,7 @@ import static java.nio.charset.StandardCharsets.UTF_8; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyList; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.argThat; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.ArgumentMatchers.isNull; @@ -59,48 +66,68 @@ import static org.mockito.Mockito.verifyZeroInteractions; import static org.mockito.Mockito.when; -public class EventHubProducerAsyncClientTest { +class EventHubProducerAsyncClientTest { private static final String HOSTNAME = "my-host-name"; private static final String EVENT_HUB_NAME = "my-event-hub-name"; @Mock private AmqpSendLink sendLink; @Mock - private AmqpSession session; + private AmqpSendLink sendLink2; + @Mock + private AmqpSendLink sendLink3; + @Mock private EventHubAmqpConnection connection; + @Mock + private EventHubAmqpConnection connection2; + @Mock + private EventHubAmqpConnection connection3; + @Mock + private TokenCredential tokenCredential; @Captor private ArgumentCaptor singleMessageCaptor; - @Captor private ArgumentCaptor> messagesCaptor; private final MessageSerializer messageSerializer = new EventHubMessageSerializer(); - private final AmqpRetryOptions retryOptions = new AmqpRetryOptions().setTryTimeout(Duration.ofSeconds(10)); + private final AmqpRetryOptions retryOptions = new AmqpRetryOptions() + .setDelay(Duration.ofMillis(500)) + .setMode(AmqpRetryMode.FIXED) + .setTryTimeout(Duration.ofSeconds(10)); + private final DirectProcessor endpointProcessor = DirectProcessor.create(); + private final FluxSink endpointSink = endpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER); private EventHubProducerAsyncClient producer; - private EventHubConnection eventHubConnection; - @Mock - private TokenCredential tokenCredential; + private EventHubConnectionProcessor connectionProcessor; private TracerProvider tracerProvider; + private ConnectionOptions connectionOptions; @BeforeEach - public void setup() { + void setup() { MockitoAnnotations.initMocks(this); tracerProvider = new TracerProvider(Collections.emptyList()); - ConnectionOptions connectionOptions = new ConnectionOptions(HOSTNAME, "event-hub-path", tokenCredential, + connectionOptions = new ConnectionOptions(HOSTNAME, "event-hub-path", tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP_WEB_SOCKETS, retryOptions, ProxyOptions.SYSTEM_DEFAULTS, Schedulers.parallel()); - eventHubConnection = new EventHubConnection(Mono.just(connection), connectionOptions); - producer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, eventHubConnection, retryOptions, tracerProvider, - messageSerializer, false); + + when(connection.getEndpointStates()).thenReturn(endpointProcessor); + endpointSink.next(AmqpEndpointState.ACTIVE); + + connectionProcessor = Mono.fromCallable(() -> connection).repeat(10).subscribeWith( + new EventHubConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), + connectionOptions.getEntityPath(), connectionOptions.getRetry())); + producer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, connectionProcessor, retryOptions, + tracerProvider, messageSerializer, false); when(sendLink.getLinkSize()).thenReturn(Mono.just(ClientConstants.MAX_MESSAGE_LENGTH_BYTES)); + when(sendLink2.getLinkSize()).thenReturn(Mono.just(ClientConstants.MAX_MESSAGE_LENGTH_BYTES)); + when(sendLink3.getLinkSize()).thenReturn(Mono.just(ClientConstants.MAX_MESSAGE_LENGTH_BYTES)); } @AfterEach - public void teardown() { + void teardown() { Mockito.framework().clearInlineMocks(); sendLink = null; connection = null; @@ -112,7 +139,7 @@ public void teardown() { * Verifies that sending multiple events will result in calling producer.send(List<Message>). */ @Test - public void sendMultipleMessages() { + void sendMultipleMessages() { // Arrange final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); @@ -122,11 +149,8 @@ public void sendMultipleMessages() { }); final SendOptions options = new SendOptions(); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); when(sendLink.send(anyList())).thenReturn(Mono.empty()); @@ -147,17 +171,15 @@ public void sendMultipleMessages() { * Verifies that sending a single event data will result in calling producer.send(Message). */ @Test - public void sendSingleMessage() { + void sendSingleMessage() { // Arrange final EventData testData = new EventData(TEST_CONTENTS.getBytes(UTF_8)); final SendOptions options = new SendOptions(); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); + when(sendLink.send(any(Message.class))).thenReturn(Mono.empty()); // Act @@ -176,17 +198,14 @@ public void sendSingleMessage() { * Verifies that a partitioned producer cannot also send events with a partition key. */ @Test - public void partitionProducerCannotSendWithPartitionKey() { + void partitionProducerCannotSendWithPartitionKey() { // Arrange final Flux testData = Flux.just( new EventData(TEST_CONTENTS.getBytes(UTF_8)), new EventData(TEST_CONTENTS.getBytes(UTF_8))); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); when(sendLink.send(anyList())).thenReturn(Mono.empty()); @@ -207,7 +226,7 @@ public void partitionProducerCannotSendWithPartitionKey() { * Verifies start and end span invoked when sending a single message. */ @Test - public void sendStartSpanSingleMessage() { + void sendStartSpanSingleMessage() { // Arrange final Tracer tracer1 = mock(Tracer.class); final List tracers = Collections.singletonList(tracer1); @@ -220,15 +239,12 @@ public void sendStartSpanSingleMessage() { final SendOptions sendOptions = new SendOptions() .setPartitionId(partitionId); final EventHubProducerAsyncClient asyncProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - eventHubConnection, retryOptions, tracerProvider, messageSerializer, false); - - when(connection.createSession(argThat(name -> name.endsWith(partitionId)))) - .thenReturn(Mono.just(session)); - when(session.createProducer( - argThat(name -> name.startsWith("PS")), - argThat(name -> name.endsWith(partitionId)), - eq(retryOptions.getTryTimeout()), any())) + connectionProcessor, retryOptions, tracerProvider, messageSerializer, false); + + when(connection.createSendLink( + argThat(name -> name.startsWith("PS")), argThat(name -> name.endsWith(partitionId)), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); + when(sendLink.send(anyList())).thenReturn(Mono.empty()); when(tracer1.start(eq("EventHubs.send"), any(), eq(ProcessKind.SEND))).thenAnswer( @@ -265,10 +281,11 @@ public void sendStartSpanSingleMessage() { } /** - * Verifies addLink method is not invoked and message/event is not stamped with context on retry (span context already present on event). + * Verifies addLink method is not invoked and message/event is not stamped with context on retry (span context + * already present on event). */ @Test - public void sendMessageRetrySpanTest() { + void sendMessageRetrySpanTest() { //Arrange final Tracer tracer1 = mock(Tracer.class); final List tracers = Collections.singletonList(tracer1); @@ -276,7 +293,7 @@ public void sendMessageRetrySpanTest() { final EventData eventData = new EventData(TEST_CONTENTS.getBytes(UTF_8)) .addContext(SPAN_CONTEXT_KEY, Context.NONE); - final EventData eventData2 = new EventData(TEST_CONTENTS.getBytes(UTF_8)) + final EventData eventData2 = new EventData(TEST_CONTENTS.getBytes(UTF_8)) .addContext(SPAN_CONTEXT_KEY, Context.NONE); final Flux testData = Flux.just(eventData, eventData2); @@ -284,14 +301,10 @@ public void sendMessageRetrySpanTest() { final SendOptions sendOptions = new SendOptions() .setPartitionId(partitionId); final EventHubProducerAsyncClient asyncProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - eventHubConnection, retryOptions, tracerProvider, messageSerializer, false); - - when(connection.createSession(argThat(name -> name.endsWith(partitionId)))) - .thenReturn(Mono.just(session)); - when(session.createProducer( - argThat(name -> name.startsWith("PS")), - argThat(name -> name.endsWith(partitionId)), - eq(retryOptions.getTryTimeout()), any())) + connectionProcessor, retryOptions, tracerProvider, messageSerializer, false); + + when(connection.createSendLink( + argThat(name -> name.startsWith("PS")), argThat(name -> name.endsWith(partitionId)), eq(retryOptions))) .thenReturn(Mono.just(sendLink)); when(sendLink.send(anyList())).thenReturn(Mono.empty()); @@ -324,17 +337,14 @@ public void sendMessageRetrySpanTest() { * Verifies that it fails if we try to send multiple messages that cannot fit in a single message batch. */ @Test - public void sendTooManyMessages() { + void sendTooManyMessages() { // Arrange int maxLinkSize = 1024; final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); // We believe 20 events is enough for that EventDataBatch to be greater than max size. @@ -356,7 +366,7 @@ public void sendTooManyMessages() { * link. */ @Test - public void createsEventDataBatch() { + void createsEventDataBatch() { // Arrange int maxLinkSize = 1024; @@ -366,11 +376,9 @@ public void createsEventDataBatch() { final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); // This event is 1024 bytes when serialized. @@ -398,25 +406,23 @@ public void createsEventDataBatch() { } /** - * Verifies that message spans are started and ended on tryAdd when creating batches to send in - * {@link EventDataBatch}. + * Verifies that message spans are started and ended on tryAdd when creating batches to send in {@link + * EventDataBatch}. */ @Test - public void startMessageSpansOnCreateBatch() { + void startMessageSpansOnCreateBatch() { // Arrange final Tracer tracer1 = mock(Tracer.class); final List tracers = Collections.singletonList(tracer1); TracerProvider tracerProvider = new TracerProvider(tracers); final EventHubProducerAsyncClient asyncProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - eventHubConnection, retryOptions, tracerProvider, messageSerializer, false); + connectionProcessor, retryOptions, tracerProvider, messageSerializer, false); final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(ClientConstants.MAX_MESSAGE_LENGTH_BYTES)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); when(tracer1.start(eq("EventHubs.message"), any(), eq(ProcessKind.MESSAGE))).thenAnswer( @@ -442,7 +448,7 @@ public void startMessageSpansOnCreateBatch() { * Verifies we can create an EventDataBatch with partition key and link size. */ @Test - public void createsEventDataBatchWithPartitionKey() { + void createsEventDataBatchWithPartitionKey() { // Arrange int maxLinkSize = 1024; @@ -451,11 +457,9 @@ public void createsEventDataBatchWithPartitionKey() { final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); // This event is 1024 bytes when serialized. @@ -475,18 +479,16 @@ public void createsEventDataBatchWithPartitionKey() { * Verifies we cannot create an EventDataBatch if the BatchOptions size is larger than the link. */ @Test - public void createEventDataBatchWhenMaxSizeIsTooBig() { + void createEventDataBatchWhenMaxSizeIsTooBig() { // Arrange int maxLinkSize = 1024; int batchSize = maxLinkSize + 10; final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); // This event is 1024 bytes when serialized. @@ -503,7 +505,7 @@ public void createEventDataBatchWhenMaxSizeIsTooBig() { * CreateBatchOptions#getMaximumSizeInBytes()}. */ @Test - public void createsEventDataBatchWithSize() { + void createsEventDataBatchWithSize() { // Arrange int maxLinkSize = 10000; int batchSize = 1024; @@ -514,11 +516,9 @@ public void createsEventDataBatchWithSize() { final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); // This event is 1024 bytes when serialized. @@ -546,7 +546,7 @@ public void createsEventDataBatchWithSize() { } @Test - public void sendEventRequired() { + void sendEventRequired() { // Arrange final EventData event = new EventData("Event-data"); final SendOptions sendOptions = new SendOptions(); @@ -559,7 +559,7 @@ public void sendEventRequired() { } @Test - public void sendEventIterableRequired() { + void sendEventIterableRequired() { // Arrange final List event = Collections.singletonList(new EventData("Event-data")); final SendOptions sendOptions = new SendOptions(); @@ -572,7 +572,7 @@ public void sendEventIterableRequired() { } @Test - public void sendEventFluxRequired() { + void sendEventFluxRequired() { // Arrange final Flux event = Flux.just(new EventData("Event-data")); final SendOptions sendOptions = new SendOptions(); @@ -585,17 +585,15 @@ public void sendEventFluxRequired() { } @Test - public void batchOptionsIsCloned() { + void batchOptionsIsCloned() { // Arrange int maxLinkSize = 1024; final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); final String originalKey = "some-key"; @@ -611,7 +609,7 @@ public void batchOptionsIsCloned() { } @Test - public void sendsAnEventDataBatch() { + void sendsAnEventDataBatch() { // Arrange int maxLinkSize = 1024; @@ -621,11 +619,9 @@ public void sendsAnEventDataBatch() { final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) .thenReturn(Mono.just(link)); // This event is 1024 bytes when serialized. @@ -656,7 +652,7 @@ public void sendsAnEventDataBatch() { * Verify we can send messages to multiple partitionIds with same sender. */ @Test - public void sendMultiplePartitions() { + void sendMultiplePartitions() { // Arrange final int count = 4; final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); @@ -668,37 +664,25 @@ public void sendMultiplePartitions() { final String partitionId1 = "my-partition-id"; final String partitionId2 = "my-partition-id-2"; - final AmqpSession partition1Session = mock(AmqpSession.class); - final AmqpSession partition2Session = mock(AmqpSession.class); - final AmqpSendLink sendLink1 = mock(AmqpSendLink.class); - final AmqpSendLink sendLink2 = mock(AmqpSendLink.class); + when(sendLink2.send(anyList())).thenReturn(Mono.empty()); + when(sendLink2.getLinkSize()).thenReturn(Mono.just(ClientConstants.MAX_MESSAGE_LENGTH_BYTES)); + when(sendLink3.send(anyList())).thenReturn(Mono.empty()); + when(sendLink3.getLinkSize()).thenReturn(Mono.just(ClientConstants.MAX_MESSAGE_LENGTH_BYTES)); - when(connection.createSession(any())).thenAnswer(mock -> { - final String entityPath = mock.getArgument(0, String.class); + // EC is the prefix they use when creating a link that sends to the service round-robin. + when(connection.createSendLink(anyString(), anyString(), any())).thenAnswer(mock -> { + final String entityPath = mock.getArgument(1, String.class); if (EVENT_HUB_NAME.equals(entityPath)) { - return Mono.just(session); + return Mono.just(sendLink); } else if (entityPath.endsWith(partitionId1)) { - return Mono.just(partition1Session); + return Mono.just(sendLink3); } else if (entityPath.endsWith(partitionId2)) { - return Mono.just(partition2Session); + return Mono.just(sendLink2); } else { return Mono.error(new IllegalArgumentException("Could not figure out entityPath: " + entityPath)); } }); - when(partition1Session.createProducer(any(), argThat(name -> name.endsWith(partitionId1)), any(), any())) - .thenReturn(Mono.just(sendLink1)); - when(partition2Session.createProducer(any(), argThat(name -> name.endsWith(partitionId2)), any(), any())) - .thenReturn(Mono.just(sendLink2)); - when(sendLink1.send(anyList())).thenReturn(Mono.empty()); - when(sendLink1.getLinkSize()).thenReturn(Mono.just(ClientConstants.MAX_MESSAGE_LENGTH_BYTES)); - when(sendLink2.send(anyList())).thenReturn(Mono.empty()); - when(sendLink2.getLinkSize()).thenReturn(Mono.just(ClientConstants.MAX_MESSAGE_LENGTH_BYTES)); - - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) - .thenReturn(Mono.just(sendLink)); when(sendLink.send(anyList())).thenReturn(Mono.empty()); // Act @@ -717,18 +701,17 @@ public void sendMultiplePartitions() { final List messagesSent = messagesCaptor.getValue(); Assertions.assertEquals(count, messagesSent.size()); - verify(sendLink1, times(1)).send(anyList()); + verify(sendLink3, times(1)).send(anyList()); verify(sendLink2, times(1)).send(anyList()); } - /** * Verifies that when we have a shared connection, the producer does not close that connection. */ @Test - public void doesNotCloseSharedConnection() { + void doesNotCloseSharedConnection() { // Arrange - EventHubConnection hubConnection = mock(EventHubConnection.class); + EventHubConnectionProcessor hubConnection = mock(EventHubConnectionProcessor.class); EventHubProducerAsyncClient sharedProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, hubConnection, retryOptions, tracerProvider, messageSerializer, true); @@ -736,16 +719,16 @@ public void doesNotCloseSharedConnection() { sharedProducer.close(); // Verify - verify(hubConnection, never()).close(); + verify(hubConnection, never()).dispose(); } /** * Verifies that when we have a non-shared connection, the producer closes that connection. */ @Test - public void closesDedicatedConnection() { + void closesDedicatedConnection() { // Arrange - EventHubConnection hubConnection = mock(EventHubConnection.class); + EventHubConnectionProcessor hubConnection = mock(EventHubConnectionProcessor.class); EventHubProducerAsyncClient dedicatedProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, hubConnection, retryOptions, tracerProvider, messageSerializer, false); @@ -753,17 +736,16 @@ public void closesDedicatedConnection() { dedicatedProducer.close(); // Verify - verify(hubConnection, times(1)).close(); + verify(hubConnection, times(1)).dispose(); } - /** * Verifies that when we have a non-shared connection, the producer closes that connection. Only once. */ @Test - public void closesDedicatedConnectionOnlyOnce() { + void closesDedicatedConnectionOnlyOnce() { // Arrange - EventHubConnection hubConnection = mock(EventHubConnection.class); + EventHubConnectionProcessor hubConnection = mock(EventHubConnectionProcessor.class); EventHubProducerAsyncClient dedicatedProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, hubConnection, retryOptions, tracerProvider, messageSerializer, false); @@ -772,11 +754,160 @@ public void closesDedicatedConnectionOnlyOnce() { dedicatedProducer.close(); // Verify - verify(hubConnection, times(1)).close(); + verify(hubConnection, times(1)).dispose(); + } + + /** + * Verifies that another link is received and we can continue publishing events on a transient failure. + */ + @Test + void reopensOnFailure() { + // Arrange + when(connection.getEndpointStates()).thenReturn(endpointProcessor); + endpointSink.next(AmqpEndpointState.ACTIVE); + + EventHubAmqpConnection[] connections = new EventHubAmqpConnection[]{ + connection, connection2, connection3 + }; + connectionProcessor = Flux.create(sink -> { + final AtomicInteger count = new AtomicInteger(); + sink.onRequest(request -> { + for (int i = 0; i < request; i++) { + final int current = count.getAndIncrement(); + final int index = current % connections.length; + sink.next(connections[index]); + } + }); + }).subscribeWith( + new EventHubConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), + connectionOptions.getEntityPath(), connectionOptions.getRetry())); + producer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, connectionProcessor, retryOptions, + tracerProvider, messageSerializer, false); + + final int count = 4; + final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); + final Flux testData = Flux.range(0, count).flatMap(number -> { + final EventData data = new EventData(contents); + return Flux.just(data); + }); + final EventData testData2 = new EventData("test"); + + // EC is the prefix they use when creating a link that sends to the service round-robin. + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) + .thenReturn(Mono.just(sendLink)); + when(sendLink.send(anyList())).thenReturn(Mono.empty()); + + final DirectProcessor connectionState2 = DirectProcessor.create(); + when(connection2.getEndpointStates()).thenReturn(connectionState2); + when(connection2.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) + .thenReturn(Mono.just(sendLink2)); + when(sendLink2.send(any(Message.class))).thenReturn(Mono.empty()); + + final DirectProcessor connectionState3 = DirectProcessor.create(); + when(connection3.getEndpointStates()).thenReturn(connectionState3); + when(connection3.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) + .thenReturn(Mono.just(sendLink3)); + when(sendLink3.send(anyList())).thenReturn(Mono.empty()); + + // Act + StepVerifier.create(producer.send(testData)) + .verifyComplete(); + + // Send in an error signal like a server busy condition. + endpointSink.error(new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-message", + new AmqpErrorContext("test-namespace"))); + + StepVerifier.create(producer.send(testData2)) + .verifyComplete(); + + // Assert + verify(sendLink).send(messagesCaptor.capture()); + final List messagesSent = messagesCaptor.getValue(); + Assertions.assertEquals(count, messagesSent.size()); + + verify(sendLink2, times(1)).send(any(Message.class)); + verifyZeroInteractions(sendLink3); } + /** + * Verifies that on a non-transient failure, no more event hub connections are recreated and we can not send events. + * An error should be propagated back to us. + */ + @Test + void closesOnNonTransientFailure() { + // Arrange + when(connection.getEndpointStates()).thenReturn(endpointProcessor); + endpointSink.next(AmqpEndpointState.ACTIVE); + + EventHubAmqpConnection[] connections = new EventHubAmqpConnection[]{ + connection, connection2, connection3 + }; + connectionProcessor = Flux.create(sink -> { + final AtomicInteger count = new AtomicInteger(); + sink.onRequest(request -> { + for (int i = 0; i < request; i++) { + final int current = count.getAndIncrement(); + final int index = current % connections.length; + sink.next(connections[index]); + } + }); + }).subscribeWith( + new EventHubConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), + connectionOptions.getEntityPath(), connectionOptions.getRetry())); + producer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, connectionProcessor, retryOptions, + tracerProvider, messageSerializer, false); + + final int count = 4; + final byte[] contents = TEST_CONTENTS.getBytes(UTF_8); + final Flux testData = Flux.range(0, count).flatMap(number -> { + final EventData data = new EventData(contents); + return Flux.just(data); + }); + final EventData testData2 = new EventData("test"); + + // EC is the prefix they use when creating a link that sends to the service round-robin. + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) + .thenReturn(Mono.just(sendLink)); + when(sendLink.send(anyList())).thenReturn(Mono.empty()); + + final DirectProcessor connectionState2 = DirectProcessor.create(); + when(connection2.getEndpointStates()).thenReturn(connectionState2); + when(connection2.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), eq(retryOptions))) + .thenReturn(Mono.just(sendLink2)); + when(sendLink2.send(any(Message.class))).thenReturn(Mono.empty()); + + final AmqpException nonTransientError = new AmqpException(false, AmqpErrorCondition.UNAUTHORIZED_ACCESS, + "Test unauthorized access", new AmqpErrorContext("test-namespace")); + + // Act + StepVerifier.create(producer.send(testData)) + .verifyComplete(); + + // Send in an error signal like authorization failure. + endpointSink.error(nonTransientError); + + StepVerifier.create(producer.send(testData2)) + .expectErrorSatisfies(error -> { + Assertions.assertTrue(error instanceof AmqpException); + + final AmqpException actual = (AmqpException) error; + Assertions.assertEquals(nonTransientError.isTransient(), actual.isTransient()); + Assertions.assertEquals(nonTransientError.getContext(), actual.getContext()); + Assertions.assertEquals(nonTransientError.getErrorCondition(), actual.getErrorCondition()); + Assertions.assertEquals(nonTransientError.getMessage(), actual.getMessage()); + }) + .verify(Duration.ofSeconds(10)); + + // Assert + verify(sendLink).send(messagesCaptor.capture()); + final List messagesSent = messagesCaptor.getValue(); + Assertions.assertEquals(count, messagesSent.size()); + + verifyZeroInteractions(sendLink2); + verifyZeroInteractions(sendLink3); + } - static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \n" + private static final String TEST_CONTENTS = "SSLorem ipsum dolor sit amet, consectetur adipiscing elit. Donec vehicula posuere lobortis. Aliquam finibus volutpat dolor, faucibus pellentesque ipsum bibendum vitae. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Ut sit amet urna hendrerit, dapibus justo a, sodales justo. Mauris finibus augue id pulvinar congue. Nam maximus luctus ipsum, at commodo ligula euismod ac. Phasellus vitae lacus sit amet diam porta placerat. \n" + "Ut sodales efficitur sapien ut posuere. Morbi sed tellus est. Proin eu erat purus. Proin massa nunc, condimentum id iaculis dignissim, consectetur et odio. Cras suscipit sem eu libero aliquam tincidunt. Nullam ut arcu suscipit, eleifend velit in, cursus libero. Ut eleifend facilisis odio sit amet feugiat. Phasellus at nunc sit amet elit sagittis commodo ac in nisi. Fusce vitae aliquam quam. Integer vel nibh euismod, tempus elit vitae, pharetra est. Duis vulputate enim a elementum dignissim. Morbi dictum enim id elit scelerisque, in elementum nulla pharetra. \n" + "Aenean aliquet aliquet condimentum. Proin dapibus dui id libero tempus feugiat. Sed commodo ligula a lectus mattis, vitae tincidunt velit auctor. Fusce quis semper dui. Phasellus eu efficitur sem. Ut non sem sit amet enim condimentum venenatis id dictum massa. Nullam sagittis lacus a neque sodales, et ultrices arcu mattis. Aliquam erat volutpat. \n" + "Aenean fringilla quam elit, id mattis purus vestibulum nec. Praesent porta eros in dapibus molestie. Vestibulum orci libero, tincidunt et turpis eget, condimentum lobortis enim. Fusce suscipit ante et mauris consequat cursus nec laoreet lorem. Maecenas in sollicitudin diam, non tincidunt purus. Nunc mauris purus, laoreet eget interdum vitae, placerat a sapien. In mi risus, blandit eu facilisis nec, molestie suscipit leo. Pellentesque molestie urna vitae dui faucibus bibendum. \n" diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerClientTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerClientTest.java index 246753b9273cf..a6a69590aee51 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerClientTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventHubProducerClientTest.java @@ -3,8 +3,8 @@ package com.azure.messaging.eventhubs; +import com.azure.core.amqp.AmqpEndpointState; import com.azure.core.amqp.AmqpRetryOptions; -import com.azure.core.amqp.AmqpSession; import com.azure.core.amqp.AmqpTransportType; import com.azure.core.amqp.ProxyOptions; import com.azure.core.amqp.exception.AmqpErrorCondition; @@ -21,6 +21,7 @@ import com.azure.core.util.tracing.Tracer; import com.azure.messaging.eventhubs.implementation.ClientConstants; import com.azure.messaging.eventhubs.implementation.EventHubAmqpConnection; +import com.azure.messaging.eventhubs.implementation.EventHubConnectionProcessor; import com.azure.messaging.eventhubs.models.CreateBatchOptions; import com.azure.messaging.eventhubs.models.SendOptions; import org.apache.qpid.proton.amqp.messaging.Section; @@ -68,9 +69,9 @@ public class EventHubProducerClientTest { @Mock private AmqpSendLink sendLink; @Mock - private AmqpSession session; - @Mock private EventHubAmqpConnection connection; + @Mock + private TokenCredential tokenCredential; @Captor private ArgumentCaptor singleMessageCaptor; @Captor @@ -79,9 +80,7 @@ public class EventHubProducerClientTest { private EventHubProducerAsyncClient asyncProducer; private AmqpRetryOptions retryOptions = new AmqpRetryOptions().setTryTimeout(Duration.ofSeconds(30)); private MessageSerializer messageSerializer = new EventHubMessageSerializer(); - private EventHubConnection linkProvider; - @Mock - private TokenCredential tokenCredential; + private EventHubConnectionProcessor connectionProcessor; @BeforeEach public void setup() { @@ -96,9 +95,13 @@ public void setup() { ConnectionOptions connectionOptions = new ConnectionOptions(HOSTNAME, "event-hub-path", tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType.AMQP_WEB_SOCKETS, retryOptions, ProxyOptions.SYSTEM_DEFAULTS, Schedulers.parallel()); - linkProvider = new EventHubConnection(Mono.just(connection), connectionOptions); - asyncProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, linkProvider, retryOptions, + connectionProcessor = Flux.create(sink -> sink.next(connection)) + .subscribeWith(new EventHubConnectionProcessor(connectionOptions.getFullyQualifiedNamespace(), + connectionOptions.getEntityPath(), connectionOptions.getRetry())); + asyncProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, connectionProcessor, retryOptions, tracerProvider, messageSerializer, false); + + when(connection.getEndpointStates()).thenReturn(Flux.create(sink -> sink.next(AmqpEndpointState.ACTIVE))); } @AfterEach @@ -118,11 +121,8 @@ public void sendSingleMessage() { final EventHubProducerClient producer = new EventHubProducerClient(asyncProducer, retryOptions.getTryTimeout()); final EventData eventData = new EventData("hello-world".getBytes(UTF_8)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), any())) .thenReturn(Mono.just(sendLink)); // Act @@ -146,15 +146,12 @@ public void sendStartSpanSingleMessage() { final List tracers = Collections.singletonList(tracer1); final TracerProvider tracerProvider = new TracerProvider(tracers); final EventHubProducerAsyncClient asyncProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - linkProvider, retryOptions, tracerProvider, messageSerializer, false); + connectionProcessor, retryOptions, tracerProvider, messageSerializer, false); final EventHubProducerClient producer = new EventHubProducerClient(asyncProducer, retryOptions.getTryTimeout()); final EventData eventData = new EventData("hello-world".getBytes(UTF_8)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), any())) .thenReturn(Mono.just(sendLink)); when(tracer1.start(eq("EventHubs.send"), any(), eq(ProcessKind.SEND))).thenAnswer( @@ -197,15 +194,12 @@ public void sendMessageRetrySpanTest() { final List tracers = Collections.singletonList(tracer1); TracerProvider tracerProvider = new TracerProvider(tracers); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), any())) .thenReturn(Mono.just(sendLink)); final EventHubProducerAsyncClient asyncProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - linkProvider, retryOptions, tracerProvider, messageSerializer, false); + connectionProcessor, retryOptions, tracerProvider, messageSerializer, false); final EventHubProducerClient producer = new EventHubProducerClient(asyncProducer, retryOptions.getTryTimeout()); final EventData eventData = new EventData("hello-world".getBytes(UTF_8)) .addContext(SPAN_CONTEXT_KEY, Context.NONE); @@ -250,11 +244,9 @@ public void sendMultipleMessages() { final SendOptions options = new SendOptions().setPartitionId(partitionId); final EventHubProducerClient producer = new EventHubProducerClient(asyncProducer, retryOptions.getTryTimeout()); - when(connection.createSession(argThat(name -> name.endsWith(partitionId)))) - .thenReturn(Mono.just(session)); - - when(session.createProducer(argThat(name -> name.startsWith("PS")), argThat(name -> name.endsWith(partitionId)), - eq(retryOptions.getTryTimeout()), any())) + // EC is the prefix they use when creating a link that sends to the service round-robin. + when(connection.createSendLink(argThat(name -> name.startsWith("PS")), + argThat(name -> name.endsWith(partitionId)), any())) .thenReturn(Mono.just(sendLink)); // Act @@ -284,11 +276,9 @@ public void createsEventDataBatch() { final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(maxLinkSize)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), any())) .thenReturn(Mono.just(link)); // This event is 1024 bytes when serialized. @@ -320,17 +310,15 @@ public void startsMessageSpanOnEventBatch() { final List tracers = Collections.singletonList(tracer1); final TracerProvider tracerProvider = new TracerProvider(tracers); final EventHubProducerAsyncClient asyncProducer = new EventHubProducerAsyncClient(HOSTNAME, EVENT_HUB_NAME, - linkProvider, retryOptions, tracerProvider, messageSerializer, false); + connectionProcessor, retryOptions, tracerProvider, messageSerializer, false); final EventHubProducerClient producer = new EventHubProducerClient(asyncProducer, retryOptions.getTryTimeout()); final AmqpSendLink link = mock(AmqpSendLink.class); when(link.getLinkSize()).thenReturn(Mono.just(ClientConstants.MAX_MESSAGE_LENGTH_BYTES)); - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) - .thenReturn(Mono.just(link)); + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), any())) + .thenReturn(Mono.just(sendLink)); when(tracer1.start(eq("EventHubs.message"), any(), eq(ProcessKind.MESSAGE))).thenAnswer( invocation -> { @@ -361,11 +349,8 @@ public void createsEventDataBatchWithPartitionKey() { int eventOverhead = 98; int maxEventPayload = maxBatchSize - eventOverhead; - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), any())) .thenReturn(Mono.just(sendLink)); // This event is 1024 bytes when serialized. @@ -398,11 +383,10 @@ public void createsEventDataBatchWithPartitionId() { int maxEventPayload = maxBatchSize - eventOverhead; String partitionId = "my-partition-id"; - when(connection.createSession(argThat(name -> name.endsWith(partitionId)))).thenReturn(Mono.just(session)); // PS is the prefix when a partition sender link is created. - when(session.createProducer(argThat(name -> name.startsWith("PS")), argThat(name -> name.endsWith(partitionId)), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("PS")), + argThat(name -> name.endsWith(partitionId)), any())) .thenReturn(Mono.just(sendLink)); // This event is 1024 bytes when serialized. @@ -434,13 +418,11 @@ public void payloadTooLarge() { int eventOverhead = 24; int maxEventPayload = maxBatchSize - eventOverhead; - when(connection.createSession(EVENT_HUB_NAME)).thenReturn(Mono.just(session)); - // EC is the prefix they use when creating a link that sends to the service round-robin. - when(session.createProducer(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), - eq(retryOptions.getTryTimeout()), any())) + when(connection.createSendLink(argThat(name -> name.startsWith("EC")), eq(EVENT_HUB_NAME), any())) .thenReturn(Mono.just(sendLink)); + // This event is 1025 bytes when serialized. final EventData event = new EventData(new byte[maxEventPayload + 1]); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientErrorHandlingTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientErrorHandlingTest.java index 21b799801c8b3..2617fbb7ba856 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientErrorHandlingTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientErrorHandlingTest.java @@ -3,23 +3,30 @@ package com.azure.messaging.eventhubs; +import static com.azure.messaging.eventhubs.EventHubClientBuilder.DEFAULT_PREFETCH_COUNT; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.when; -import com.azure.messaging.eventhubs.implementation.ClientConstants; import com.azure.messaging.eventhubs.implementation.PartitionProcessor; import com.azure.messaging.eventhubs.models.Checkpoint; +import com.azure.messaging.eventhubs.models.CloseContext; import com.azure.messaging.eventhubs.models.ErrorContext; import com.azure.messaging.eventhubs.models.EventContext; +import com.azure.messaging.eventhubs.models.EventPosition; +import com.azure.messaging.eventhubs.models.InitializationContext; +import com.azure.messaging.eventhubs.models.PartitionContext; +import com.azure.messaging.eventhubs.models.PartitionEvent; import com.azure.messaging.eventhubs.models.PartitionOwnership; -import java.net.URI; -import java.net.URISyntaxException; +import com.azure.messaging.eventhubs.models.ReceiveOptions; +import java.util.HashMap; import java.util.List; -import java.util.Locale; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; import java.util.stream.Stream; import org.junit.jupiter.api.Assertions; 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; @@ -35,15 +42,6 @@ public class EventProcessorClientErrorHandlingTest { private static final String NAMESPACE_NAME = "dummyNamespaceName"; private static final String DEFAULT_DOMAIN_NAME = "servicebus.windows.net/"; - private static final String EVENT_HUB_NAME = "eventHubName"; - private static final String SHARED_ACCESS_KEY_NAME = "dummySasKeyName"; - private static final String SHARED_ACCESS_KEY = "dummySasKey"; - private static final String ENDPOINT = getURI(ClientConstants.ENDPOINT_FORMAT, NAMESPACE_NAME, DEFAULT_DOMAIN_NAME) - .toString(); - - private static final String CORRECT_CONNECTION_STRING = String - .format("Endpoint=%s;SharedAccessKeyName=%s;SharedAccessKey=%s;EntityPath=%s", - ENDPOINT, SHARED_ACCESS_KEY_NAME, SHARED_ACCESS_KEY, EVENT_HUB_NAME); @Mock private EventHubClientBuilder eventHubClientBuilder; @@ -54,16 +52,10 @@ public class EventProcessorClientErrorHandlingTest { @Mock private EventHubConsumerAsyncClient eventHubConsumer; - private CountDownLatch countDownLatch; + @Mock + private EventData eventData1; - private static URI getURI(String endpointFormat, String namespace, String domainName) { - try { - return new URI(String.format(Locale.US, endpointFormat, namespace, domainName)); - } catch (URISyntaxException exception) { - throw new IllegalArgumentException(String.format(Locale.US, - "Invalid namespace name: %s", namespace), exception); - } - } + private CountDownLatch countDownLatch; @BeforeEach public void setup() { @@ -85,7 +77,52 @@ public void testCheckpointStoreErrors(CheckpointStore checkpointStore) throws In Assertions.assertEquals("NONE", errorContext.getPartitionContext().getPartitionId()); Assertions.assertEquals("cg", errorContext.getPartitionContext().getConsumerGroup()); Assertions.assertTrue(errorContext.getThrowable() instanceof IllegalStateException); - }); + }, new HashMap<>()); + client.start(); + boolean completed = countDownLatch.await(3, TimeUnit.SECONDS); + client.stop(); + Assertions.assertTrue(completed); + } + + @Test + public void testProcessEventHandlerError() throws InterruptedException { + countDownLatch = new CountDownLatch(1); + when(eventHubAsyncClient.createConsumer("cg", DEFAULT_PREFETCH_COUNT)).thenReturn(eventHubConsumer); + when(eventHubConsumer.receiveFromPartition(anyString(), any(EventPosition.class), any(ReceiveOptions.class))) + .thenReturn(Flux.just(getEvent(eventData1))); + EventProcessorClient client = new EventProcessorClient(eventHubClientBuilder, "cg", + () -> new BadProcessEventHandler(countDownLatch), new InMemoryCheckpointStore(), false, + null, errorContext -> { }, new HashMap<>()); + client.start(); + boolean completed = countDownLatch.await(3, TimeUnit.SECONDS); + client.stop(); + Assertions.assertTrue(completed); + } + + @Test + public void testInitHandlerError() throws InterruptedException { + countDownLatch = new CountDownLatch(1); + when(eventHubAsyncClient.createConsumer("cg", DEFAULT_PREFETCH_COUNT)).thenReturn(eventHubConsumer); + when(eventHubConsumer.receiveFromPartition(anyString(), any(EventPosition.class), any(ReceiveOptions.class))) + .thenReturn(Flux.just(getEvent(eventData1))); + EventProcessorClient client = new EventProcessorClient(eventHubClientBuilder, "cg", + () -> new BadInitHandler(countDownLatch), new InMemoryCheckpointStore(), false, + null, errorContext -> { }, new HashMap<>()); + client.start(); + boolean completed = countDownLatch.await(3, TimeUnit.SECONDS); + client.stop(); + Assertions.assertTrue(completed); + } + + @Test + public void testCloseHandlerError() throws InterruptedException { + countDownLatch = new CountDownLatch(1); + when(eventHubAsyncClient.createConsumer("cg", DEFAULT_PREFETCH_COUNT)).thenReturn(eventHubConsumer); + when(eventHubConsumer.receiveFromPartition(anyString(), any(EventPosition.class), any(ReceiveOptions.class))) + .thenReturn(Flux.just(getEvent(eventData1))); + EventProcessorClient client = new EventProcessorClient(eventHubClientBuilder, "cg", + () -> new BadCloseHandler(countDownLatch), new InMemoryCheckpointStore(), false, + null, errorContext -> { }, new HashMap<>()); client.start(); boolean completed = countDownLatch.await(3, TimeUnit.SECONDS); client.stop(); @@ -99,6 +136,11 @@ private static Stream checkpointStoreSupplier() { Arguments.of(new ListCheckpointErrorStore())); } + private PartitionEvent getEvent(EventData event) { + PartitionContext context = new PartitionContext("ns", "foo", "bar", "baz"); + return new PartitionEvent(context, event, null); + } + private static class ListOwnershipErrorStore implements CheckpointStore { @@ -191,4 +233,75 @@ public void processError(ErrorContext errorContext) { return; } } + + private static final class BadProcessEventHandler extends PartitionProcessor { + + CountDownLatch countDownLatch; + + BadProcessEventHandler(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + @Override + public void processEvent(EventContext eventContext) { + countDownLatch.countDown(); + throw new IllegalStateException("Process event error"); + } + + @Override + public void processError(ErrorContext errorContext) { + Assertions.fail("Process error handler should not be called when process event throws exception"); + return; + } + } + + private static final class BadInitHandler extends PartitionProcessor { + + CountDownLatch countDownLatch; + + BadInitHandler(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + @Override + public void initialize(InitializationContext initContext) { + countDownLatch.countDown(); + throw new IllegalStateException("Init error"); + } + + @Override + public void processEvent(EventContext eventContext) { + Assertions.fail("Process event handler should not be called when there's an error during initialization"); + } + + @Override + public void processError(ErrorContext errorContext) { + Assertions.fail("Process error handler should not be called when process event throws exception"); + return; + } + } + + private static final class BadCloseHandler extends PartitionProcessor { + + CountDownLatch countDownLatch; + BadCloseHandler(CountDownLatch countDownLatch) { + this.countDownLatch = countDownLatch; + } + + @Override + public void close(CloseContext closeContext) { + countDownLatch.countDown(); + throw new IllegalStateException("Close error"); + } + + @Override + public void processEvent(EventContext eventContext) { + // do nothing + } + + @Override + public void processError(ErrorContext errorContext) { + // do nothing + } + } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientTest.java index 7f1f47ad825ba..1cc88baed6eda 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/EventProcessorClientTest.java @@ -140,7 +140,7 @@ public void testWithSimplePartitionProcessor() throws Exception { // Act final EventProcessorClient eventProcessorClient = new EventProcessorClient(eventHubClientBuilder, "test-consumer", - () -> testPartitionProcessor, checkpointStore, false, tracerProvider, ec -> { }); + () -> testPartitionProcessor, checkpointStore, false, tracerProvider, ec -> { }, new HashMap<>()); eventProcessorClient.start(); TimeUnit.SECONDS.sleep(10); eventProcessorClient.stop(); @@ -170,117 +170,6 @@ public void testWithSimplePartitionProcessor() throws Exception { verify(consumer1, atLeastOnce()).close(); } - /** - * Tests {@link EventProcessorClient} with a partition processor that throws an exception when processing an event. - * - * @throws Exception if an error occurs while running the test. - */ - @Test - public void testWithFaultyPartitionProcessor() throws Exception { - // Arrange - final Tracer tracer1 = mock(Tracer.class); - final List tracers = Collections.singletonList(tracer1); - TracerProvider tracerProvider = new TracerProvider(tracers); - when(eventHubClientBuilder.buildAsyncClient()).thenReturn(eventHubAsyncClient); - when(eventHubAsyncClient.getFullyQualifiedNamespace()).thenReturn("test-ns"); - when(eventHubAsyncClient.getEventHubName()).thenReturn("test-eh"); - when(eventHubAsyncClient.getPartitionIds()).thenReturn(Flux.just("1")); - when(eventHubAsyncClient - .createConsumer(anyString(), anyInt())) - .thenReturn(consumer1); - when(consumer1.receiveFromPartition(anyString(), any(EventPosition.class), any(ReceiveOptions.class))).thenReturn(Flux.just(getEvent(eventData1))); - String diagnosticId = "00-08ee063508037b1719dddcbf248e30e2-1365c684eb25daed-01"; - - final InMemoryCheckpointStore checkpointStore = new InMemoryCheckpointStore(); - final FaultyPartitionProcessor faultyPartitionProcessor = new FaultyPartitionProcessor(); - - when(tracer1.extractContext(eq(diagnosticId), any())).thenAnswer( - invocation -> { - Context passed = invocation.getArgument(1, Context.class); - return passed.addData(SPAN_CONTEXT_KEY, "value"); - } - ); - when(tracer1.start(eq("EventHubs.process"), any(), eq(ProcessKind.PROCESS))).thenAnswer( - invocation -> { - Context passed = invocation.getArgument(1, Context.class); - return passed.addData(SPAN_CONTEXT_KEY, "value1") - .addData("scope", (Closeable) () -> { - }) - .addData(PARENT_SPAN_KEY, "value2"); - } - ); - // Act - final EventProcessorClient eventProcessorClient = new EventProcessorClient(eventHubClientBuilder, "test-consumer", - () -> faultyPartitionProcessor, checkpointStore, false, tracerProvider, ec -> { }); - - eventProcessorClient.start(); - TimeUnit.SECONDS.sleep(10); - eventProcessorClient.stop(); - - // Assert - assertTrue(faultyPartitionProcessor.error); - } - - /** - * Tests process start spans error messages invoked for {@link EventProcessorClient}. - * - * @throws Exception if an error occurs while running the test. - */ - @Test - public void testErrorProcessSpans() throws Exception { - //Arrange - final Tracer tracer1 = mock(Tracer.class); - final List tracers = Collections.singletonList(tracer1); - TracerProvider tracerProvider = new TracerProvider(tracers); - when(eventHubClientBuilder.buildAsyncClient()).thenReturn(eventHubAsyncClient); - when(eventHubAsyncClient.getFullyQualifiedNamespace()).thenReturn("test-ns"); - when(eventHubAsyncClient.getEventHubName()).thenReturn("test-eh"); - when(eventHubAsyncClient.getPartitionIds()).thenReturn(Flux.just("1")); - when(eventHubAsyncClient - .createConsumer(anyString(), anyInt())) - .thenReturn(consumer1); - when(eventData1.getSequenceNumber()).thenReturn(1L); - when(eventData2.getSequenceNumber()).thenReturn(2L); - when(eventData1.getOffset()).thenReturn(1L); - when(eventData2.getOffset()).thenReturn(100L); - - String diagnosticId = "00-08ee063508037b1719dddcbf248e30e2-1365c684eb25daed-01"; - Map properties = new HashMap<>(); - properties.put(DIAGNOSTIC_ID_KEY, diagnosticId); - - when(eventData1.getProperties()).thenReturn(properties); - when(consumer1.receiveFromPartition(anyString(), any(EventPosition.class), any(ReceiveOptions.class))).thenReturn(Flux.just(getEvent(eventData1))); - when(tracer1.extractContext(eq(diagnosticId), any())).thenAnswer( - invocation -> { - Context passed = invocation.getArgument(1, Context.class); - return passed.addData(SPAN_CONTEXT_KEY, "value"); - } - ); - when(tracer1.start(eq("EventHubs.process"), any(), eq(ProcessKind.PROCESS))).thenAnswer( - invocation -> { - Context passed = invocation.getArgument(1, Context.class); - return passed.addData(SPAN_CONTEXT_KEY, "value1") - .addData("scope", (Closeable) () -> { - }) - .addData(PARENT_SPAN_KEY, "value2"); - } - ); - - final InMemoryCheckpointStore checkpointStore = new InMemoryCheckpointStore(); - - //Act - final EventProcessorClient eventProcessorClient = new EventProcessorClient(eventHubClientBuilder, "test-consumer", - FaultyPartitionProcessor::new, checkpointStore, false, tracerProvider, ec -> { }); - eventProcessorClient.start(); - TimeUnit.SECONDS.sleep(10); - eventProcessorClient.stop(); - - //Assert - verify(tracer1, times(1)).extractContext(eq(diagnosticId), any()); - verify(tracer1, times(1)).start(eq("EventHubs.process"), any(), eq(ProcessKind.PROCESS)); - verify(tracer1, times(1)).end(eq(""), any(IllegalStateException.class), any()); - } - /** * Tests process start spans invoked for {@link EventProcessorClient}. * @@ -329,7 +218,7 @@ public void testProcessSpans() throws Exception { //Act final EventProcessorClient eventProcessorClient = new EventProcessorClient(eventHubClientBuilder, "test-consumer", - TestPartitionProcessor::new, checkpointStore, false, tracerProvider, ec -> { }); + TestPartitionProcessor::new, checkpointStore, false, tracerProvider, ec -> { }, new HashMap<>()); eventProcessorClient.start(); TimeUnit.SECONDS.sleep(10); @@ -354,7 +243,7 @@ public void testWithMultiplePartitions() throws Exception { identifiers.add("1"); identifiers.add("2"); identifiers.add("3"); - final EventPosition position = EventPosition.earliest(); + final EventPosition position = EventPosition.latest(); when(eventHubClientBuilder.buildAsyncClient()).thenReturn(eventHubAsyncClient); when(eventHubAsyncClient.getPartitionIds()).thenReturn(Flux.just("1", "2", "3")); @@ -391,7 +280,7 @@ public void testWithMultiplePartitions() throws Exception { // Act final EventProcessorClient eventProcessorClient = new EventProcessorClient(eventHubClientBuilder, "test-consumer", - TestPartitionProcessor::new, checkpointStore, false, tracerProvider, ec -> { }); + TestPartitionProcessor::new, checkpointStore, false, tracerProvider, ec -> { }, new HashMap<>()); eventProcessorClient.start(); final boolean completed = count.await(10, TimeUnit.SECONDS); eventProcessorClient.stop(); @@ -420,21 +309,6 @@ private PartitionEvent getEvent(EventData event) { return new PartitionEvent(context, event, null); } - private static final class FaultyPartitionProcessor extends PartitionProcessor { - - boolean error; - - @Override - public void processError(ErrorContext errorContext) { - error = true; - } - - @Override - public void processEvent(EventContext partitionEvent) { - throw new IllegalStateException(); - } - } - private static final class TestPartitionProcessor extends PartitionProcessor { @Override 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 e6f1fc55ec330..8c92b110a2c9b 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 @@ -21,7 +21,9 @@ import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.TestInfo; import org.mockito.Mockito; +import reactor.core.scheduler.Scheduler; import reactor.core.scheduler.Schedulers; +import reactor.test.StepVerifier; import java.io.Closeable; import java.io.IOException; @@ -51,6 +53,7 @@ public abstract class IntegrationTestBase extends TestBase { private ConnectionStringProperties properties; private String testName; + private final Scheduler scheduler = Schedulers.parallel(); protected IntegrationTestBase(ClientLogger logger) { this.logger = logger; @@ -65,6 +68,8 @@ public void setupTest(TestInfo testInfo) { properties = new ConnectionStringProperties(getConnectionString()); + StepVerifier.setDefaultTimeout(TIMEOUT); + beforeTest(); } @@ -73,6 +78,7 @@ public void setupTest(TestInfo testInfo) { @AfterEach public void teardownTest(TestInfo testInfo) { logger.info("[{}]: Performing test clean-up.", testInfo.getDisplayName()); + StepVerifier.resetDefaultTimeout(); afterTest(); // Tear down any inline mocks to avoid memory leaks. @@ -161,7 +167,7 @@ protected EventHubClientBuilder createBuilder(boolean useCredentials) { .proxyOptions(ProxyOptions.SYSTEM_DEFAULTS) .retry(RETRY_OPTIONS) .transportType(AmqpTransportType.AMQP) - .scheduler(Schedulers.newParallel("eh-integration")); + .scheduler(scheduler); if (useCredentials) { final String fqdn = getFullyQualifiedDomainName(); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java index 19ab8b8646575..56ac5df702f5e 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/InteropAmqpPropertiesTest.java @@ -26,7 +26,6 @@ import java.util.HashMap; import java.util.Map; import java.util.UUID; -import java.util.concurrent.atomic.AtomicReference; import static com.azure.core.amqp.AmqpMessageConstant.ENQUEUED_TIME_UTC_ANNOTATION_NAME; import static com.azure.core.amqp.AmqpMessageConstant.OFFSET_ANNOTATION_NAME; @@ -72,7 +71,6 @@ protected void afterTest() { @Test public void interoperableWithDirectProtonAmqpMessage() { // Arrange - final AtomicReference receivedEventData = new AtomicReference<>(); final String messageTrackingValue = UUID.randomUUID().toString(); final HashMap applicationProperties = new HashMap<>(); @@ -119,23 +117,9 @@ public void interoperableWithDirectProtonAmqpMessage() { .filter(event -> isMatchingEvent(event, messageTrackingValue)).take(1).map(PartitionEvent::getData)) .assertNext(event -> { validateAmqpProperties(message, expectedAnnotations, applicationProperties, event); - receivedEventData.set(event); }) .expectComplete() .verify(TIMEOUT); - - Assertions.assertNotNull(receivedEventData.get()); - - System.out.println("Sending another event we received."); - final EventPosition enqueuedTime2 = EventPosition.fromEnqueuedTime(Instant.now()); - producer.send(receivedEventData.get(), sendOptions).block(TIMEOUT); - -// .filter(event -> isMatchingEvent(event, messageTrackingValue)) - StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, enqueuedTime2) - .take(1).map(PartitionEvent::getData)) - .assertNext(event -> validateAmqpProperties(message, expectedAnnotations, applicationProperties, event)) - .expectComplete() - .verify(TIMEOUT); } private void validateAmqpProperties(Message message, Map messageAnnotations, diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancerTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancerTest.java index 6947ceccb41c7..671ed8dd3b0f6 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancerTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/PartitionBasedLoadBalancerTest.java @@ -14,6 +14,7 @@ import com.azure.messaging.eventhubs.models.PartitionEvent; import com.azure.messaging.eventhubs.models.PartitionOwnership; import com.azure.messaging.eventhubs.models.ReceiveOptions; +import java.util.HashMap; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; @@ -312,7 +313,7 @@ public void testReceiveFailure() throws Exception { .thenReturn(Flux.error(new IllegalStateException())); PartitionPumpManager partitionPumpManager = new PartitionPumpManager(checkpointStore, - () -> partitionProcessor, eventHubClientBuilder, false, tracerProvider); + () -> partitionProcessor, eventHubClientBuilder, false, tracerProvider, new HashMap<>()); PartitionBasedLoadBalancer loadBalancer = new PartitionBasedLoadBalancer(checkpointStore, eventHubAsyncClient, fqNamespace, eventHubName, consumerGroupName, "owner", TimeUnit.SECONDS.toSeconds(5), partitionPumpManager, ec -> { @@ -337,7 +338,7 @@ public void testCheckpointStoreFailure() throws Exception { List partitionIds = Arrays.asList("1", "2", "3"); when(eventHubAsyncClient.getPartitionIds()).thenReturn(Flux.fromIterable(partitionIds)); PartitionPumpManager partitionPumpManager = new PartitionPumpManager(checkpointStore, - () -> partitionProcessor, eventHubClientBuilder, false, tracerProvider); + () -> partitionProcessor, eventHubClientBuilder, false, tracerProvider, new HashMap<>()); PartitionBasedLoadBalancer loadBalancer = new PartitionBasedLoadBalancer(checkpointStore, eventHubAsyncClient, fqNamespace, eventHubName, consumerGroupName, "owner", TimeUnit.SECONDS.toSeconds(5), partitionPumpManager, ec -> { @@ -363,7 +364,7 @@ public void testEventHubClientFailure() { List partitionIds = new ArrayList<>(); when(eventHubAsyncClient.getPartitionIds()).thenReturn(Flux.fromIterable(partitionIds)); PartitionPumpManager partitionPumpManager = new PartitionPumpManager(checkpointStore, - () -> partitionProcessor, eventHubClientBuilder, false, tracerProvider); + () -> partitionProcessor, eventHubClientBuilder, false, tracerProvider, new HashMap<>()); PartitionBasedLoadBalancer loadBalancer = new PartitionBasedLoadBalancer(checkpointStore, eventHubAsyncClient, fqNamespace, eventHubName, consumerGroupName, "owner", TimeUnit.SECONDS.toSeconds(5), partitionPumpManager, ec -> { @@ -460,7 +461,7 @@ public void processError(ErrorContext eventProcessingErrorContext) { eventProcessingErrorContext.getPartitionContext().getPartitionId(), eventProcessingErrorContext.getThrowable()); } - }, eventHubClientBuilder, false, tracerProvider); + }, eventHubClientBuilder, false, tracerProvider, new HashMap<>()); return new PartitionBasedLoadBalancer(checkpointStore, eventHubAsyncClient, fqNamespace, eventHubName, consumerGroupName, owner, TimeUnit.SECONDS.toSeconds(5), partitionPumpManager, ec -> { }); diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyReceiveTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyReceiveTest.java index f6cc19fb49ba2..23375ccff0ab3 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyReceiveTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxyReceiveTest.java @@ -101,6 +101,7 @@ public void testReceiverStartOfStreamFilters() { StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, EventPosition.fromEnqueuedTime(testData.getEnqueuedTime())) .take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) - .verifyComplete(); + .expectComplete() + .verify(TIMEOUT); } } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxySendTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxySendTest.java index 5d689acf78b6d..7de2d3698e96b 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxySendTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/ProxySendTest.java @@ -26,7 +26,7 @@ import java.util.UUID; public class ProxySendTest extends IntegrationTestBase { - private static final int PROXY_PORT = 8899; + private static final int PROXY_PORT = 8999; private static final String PARTITION_ID = "1"; private static final int NUMBER_OF_EVENTS = 25; @@ -97,13 +97,15 @@ public void sendEvents() { try { // Act StepVerifier.create(producer.send(events, options)) - .verifyComplete(); + .expectComplete() + .verify(TIMEOUT); // Assert StepVerifier.create(consumer.receiveFromPartition(PARTITION_ID, EventPosition.fromEnqueuedTime(sendTime)) .filter(x -> TestUtils.isMatchingEvent(x, messageId)).take(NUMBER_OF_EVENTS)) .expectNextCount(NUMBER_OF_EVENTS) - .verifyComplete(); + .expectComplete() + .verify(TIMEOUT); } finally { dispose(producer, consumer); } diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/CBSChannelTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/CBSChannelTest.java index 3a6b4bb3aa934..51458dbec9ae9 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/CBSChannelTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/CBSChannelTest.java @@ -23,7 +23,9 @@ import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.IntegrationTestBase; +import java.util.Map; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -45,11 +47,20 @@ public class CBSChannelTest extends IntegrationTestBase { private AzureTokenManagerProvider azureTokenManagerProvider; @Mock private MessageSerializer messageSerializer; + private static String product; + private static String clientVersion; public CBSChannelTest() { super(new ClientLogger(CBSChannelTest.class)); } + @BeforeAll + public static void init() { + Map properties = CoreUtils.getProperties("azure-messaging-eventhubs.properties"); + product = properties.get("name"); + clientVersion = properties.get("version"); + } + @Override protected void beforeTest() { MockitoAnnotations.initMocks(this); @@ -69,7 +80,7 @@ protected void beforeTest() { ReactorProvider reactorProvider = new ReactorProvider(); ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(reactorProvider); connection = new TestReactorConnection(CONNECTION_ID, connectionOptions, reactorProvider, handlerProvider, - azureTokenManagerProvider, messageSerializer); + azureTokenManagerProvider, messageSerializer, product, clientVersion); final Mono requestResponseChannel = connection.getCBSChannel(); @@ -126,11 +137,13 @@ public void unsuccessfulAuthorize() { } private static final class TestReactorConnection extends ReactorConnection { + private TestReactorConnection(String connectionId, ConnectionOptions connectionOptions, - ReactorProvider reactorProvider, ReactorHandlerProvider handlerProvider, - TokenManagerProvider tokenManagerProvider, MessageSerializer messageSerializer) { + ReactorProvider reactorProvider, ReactorHandlerProvider handlerProvider, + TokenManagerProvider tokenManagerProvider, MessageSerializer messageSerializer, + String product, String clientVersion) { super(connectionId, connectionOptions, reactorProvider, handlerProvider, tokenManagerProvider, - messageSerializer); + messageSerializer, product, clientVersion); } private Mono getCBSChannel() { diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EventHubConnectionProcessorTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EventHubConnectionProcessorTest.java new file mode 100644 index 0000000000000..149314522cc53 --- /dev/null +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EventHubConnectionProcessorTest.java @@ -0,0 +1,305 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.messaging.eventhubs.implementation; + +import com.azure.core.amqp.AmqpEndpointState; +import com.azure.core.amqp.AmqpRetryOptions; +import com.azure.core.amqp.AmqpShutdownSignal; +import com.azure.core.amqp.exception.AmqpErrorCondition; +import com.azure.core.amqp.exception.AmqpErrorContext; +import com.azure.core.amqp.exception.AmqpException; +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.MockitoAnnotations; +import org.reactivestreams.Subscription; +import reactor.core.publisher.DirectProcessor; +import reactor.core.publisher.Flux; +import reactor.core.publisher.FluxSink; +import reactor.core.publisher.Mono; +import reactor.test.StepVerifier; + +import java.time.Duration; +import java.util.Objects; +import java.util.concurrent.atomic.AtomicInteger; + +import static org.mockito.ArgumentMatchers.eq; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +/** + * Tests for {@link EventHubConnectionProcessor}. + */ +public class EventHubConnectionProcessorTest { + private static final String NAMESPACE = "test-namespace.eventhubs.com"; + private static final String EVENT_HUB_NAME = "test-event-hub-name"; + private static final AmqpRetryOptions AMQP_RETRY_OPTIONS = new AmqpRetryOptions().setMaxRetries(2) + .setDelay(Duration.ofSeconds(10)); + + @Mock + private EventHubAmqpConnection connection; + @Mock + private EventHubAmqpConnection connection2; + @Mock + private EventHubAmqpConnection connection3; + + private final Duration timeout = Duration.ofSeconds(10); + private DirectProcessor endpointProcessor = DirectProcessor.create(); + private DirectProcessor shutdownSignalProcessor = DirectProcessor.create(); + private EventHubConnectionProcessor eventHubConnectionProcessor = new EventHubConnectionProcessor(NAMESPACE, + EVENT_HUB_NAME, AMQP_RETRY_OPTIONS); + + @BeforeEach + public void setup() { + MockitoAnnotations.initMocks(this); + + when(connection.getEndpointStates()).thenReturn(endpointProcessor); + when(connection.getShutdownSignals()).thenReturn(shutdownSignalProcessor); + } + + /** + * Verifies that we can get a new connection. + */ + @Test + public void createsNewConnection() { + EventHubConnectionProcessor processor = Mono.fromCallable(() -> connection).repeat() + .subscribeWith(eventHubConnectionProcessor); + + StepVerifier.create(processor) + .expectNext(connection) + .expectComplete() + .verify(timeout); + } + + /** + * Verifies that we can get the same, open connection when subscribing twice. + */ + @Test + public void sameConnectionReturned() { + // Arrange + EventHubConnectionProcessor processor = Mono.fromCallable(() -> connection).repeat() + .subscribeWith(eventHubConnectionProcessor); + + // Act & Assert + StepVerifier.create(processor) + .expectNext(connection) + .expectComplete() + .verify(timeout); + + StepVerifier.create(processor) + .expectNext(connection) + .expectComplete() + .verify(timeout); + } + + /** + * Verifies that we can get the next connection when the first one is closed. + */ + @Test + public void newConnectionOnClose() { + // Arrange + final EventHubAmqpConnection[] connections = new EventHubAmqpConnection[]{ + connection, + connection2, + connection3 + }; + + final Flux connectionsSink = createSink(connections); + final EventHubConnectionProcessor processor = connectionsSink.subscribeWith(eventHubConnectionProcessor); + final FluxSink endpointSink = endpointProcessor.sink(); + final DirectProcessor connection2EndpointProcessor = DirectProcessor.create(); + final FluxSink connection2Endpoint = connection2EndpointProcessor.sink(FluxSink.OverflowStrategy.BUFFER); + connection2Endpoint.next(AmqpEndpointState.ACTIVE); + + when(connection2.getEndpointStates()).thenReturn(connection2EndpointProcessor); + + // Act & Assert + + // Verify that we get the first connection. + StepVerifier.create(processor) + .then(() -> endpointSink.next(AmqpEndpointState.ACTIVE)) + .expectNext(connection) + .expectComplete() + .verify(timeout); + + // Close that connection. + endpointSink.complete(); + + // Expect that the next connection is returned to us. + StepVerifier.create(processor) + .expectNext(connection2) + .expectComplete() + .verify(timeout); + + // Close connection 2 + connection2Endpoint.complete(); + + // Expect that the new connection is returned again. + StepVerifier.create(processor) + .expectNext(connection3) + .expectComplete() + .verify(timeout); + + // Expect that the new connection is returned again. + StepVerifier.create(processor) + .expectNext(connection3) + .expectComplete() + .verify(timeout); + } + + /** + * Verifies that we can get the next connection when the first one encounters a retryable error. + */ + @Test + public void newConnectionOnRetryableError() { + // Arrange + final EventHubAmqpConnection[] connections = new EventHubAmqpConnection[]{ + connection, + connection2 + }; + final AmqpException amqpException = new AmqpException(true, AmqpErrorCondition.SERVER_BUSY_ERROR, "Test-error", + new AmqpErrorContext("test-namespace")); + + final Flux connectionsSink = createSink(connections); + final EventHubConnectionProcessor processor = connectionsSink.subscribeWith(eventHubConnectionProcessor); + final FluxSink endpointSink = endpointProcessor.sink(); + + // Act & Assert + // Verify that we get the first connection. + StepVerifier.create(processor) + .then(() -> endpointSink.next(AmqpEndpointState.ACTIVE)) + .expectNext(connection) + .expectComplete() + .verify(timeout); + + endpointSink.error(amqpException); + + // Expect that the next connection is returned to us. + StepVerifier.create(processor) + .expectNext(connection2) + .expectComplete() + .verify(timeout); + + // Expect that the next connection is returned to us. + StepVerifier.create(processor) + .expectNext(connection2) + .expectComplete() + .verify(timeout); + } + + /** + * Verifies that an error is propagated when the first connection encounters a non-retryable error. + */ + @Test + public void nonRetryableError() { + // Arrange + final EventHubAmqpConnection[] connections = new EventHubAmqpConnection[]{ + connection, + connection2 + }; + final AmqpException amqpException = new AmqpException(false, AmqpErrorCondition.ILLEGAL_STATE, "Test-error", + new AmqpErrorContext("test-namespace")); + + final Flux connectionsSink = createSink(connections); + final EventHubConnectionProcessor processor = connectionsSink.subscribeWith(eventHubConnectionProcessor); + final FluxSink endpointSink = endpointProcessor.sink(); + + // Act & Assert + // Verify that we get the first connection. + StepVerifier.create(processor) + .then(() -> endpointSink.next(AmqpEndpointState.ACTIVE)) + .expectNext(connection) + .expectComplete() + .verify(timeout); + + endpointSink.error(amqpException); + + // Expect that the error is returned to us. + StepVerifier.create(processor) + .expectErrorMatches(error -> Objects.equals(amqpException, error)) + .verify(timeout); + + // Expect that the error is returned to us again. + StepVerifier.create(processor) + .expectErrorMatches(error -> Objects.equals(amqpException, error)) + .verify(timeout); + } + + /** + * Verifies that when there are no subscribers, no request is fetched from upstream. + */ + @Test + public void noSubscribers() { + // Arrange + final Subscription subscription = mock(Subscription.class); + + // Act + eventHubConnectionProcessor.onSubscribe(subscription); + + // Assert + verify(subscription).request(eq(0L)); + } + + /** + * Verifies that when the processor has completed (ie. the instance is closed), no more connections are emitted. + */ + @Test + public void completesWhenTerminated() { + // Arrange + final EventHubAmqpConnection[] connections = new EventHubAmqpConnection[]{ + connection, + }; + + final Flux connectionsSink = createSink(connections); + final EventHubConnectionProcessor processor = connectionsSink.subscribeWith(eventHubConnectionProcessor); + final FluxSink endpointSink = endpointProcessor.sink(); + + // Act & Assert + // Verify that we get the first connection. + StepVerifier.create(eventHubConnectionProcessor) + .then(() -> endpointSink.next(AmqpEndpointState.ACTIVE)) + .expectNext(connection) + .expectComplete() + .verify(timeout); + + eventHubConnectionProcessor.onComplete(); + + // Verify that it completes without emitting a connection. + StepVerifier.create(processor) + .expectComplete() + .verify(timeout); + } + + @Test + public void requiresNonNull() { + Assertions.assertThrows(NullPointerException.class, + () -> eventHubConnectionProcessor.onNext(null)); + + Assertions.assertThrows(NullPointerException.class, + () -> eventHubConnectionProcessor.onError(null)); + } + + private static Flux createSink(EventHubAmqpConnection[] connections) { + return Flux.create(emitter -> { + final AtomicInteger counter = new AtomicInteger(); + + emitter.onRequest(request -> { + for (int i = 0; i < request; i++) { + final int index = counter.getAndIncrement(); + + if (index == connections.length) { + emitter.error(new RuntimeException(String.format( + "Cannot emit more. Index: %s. # of Connections: %s", + index, connections.length))); + break; + } + + emitter.next(connections[index]); + } + }); + }, FluxSink.OverflowStrategy.BUFFER); + } +} diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EventHubReactorConnectionTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EventHubReactorConnectionTest.java index 485612210e051..bc483e58368a1 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EventHubReactorConnectionTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/EventHubReactorConnectionTest.java @@ -15,11 +15,14 @@ import com.azure.core.amqp.implementation.TokenManagerProvider; import com.azure.core.amqp.implementation.handler.ConnectionHandler; import com.azure.core.credential.TokenCredential; +import com.azure.core.util.CoreUtils; +import java.util.Map; import org.apache.qpid.proton.engine.Connection; import org.apache.qpid.proton.reactor.Reactor; import org.apache.qpid.proton.reactor.Selectable; import org.junit.jupiter.api.AfterEach; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.Mock; @@ -55,10 +58,20 @@ public class EventHubReactorConnectionTest { @Mock private ReactorHandlerProvider handlerProvider; private ConnectionOptions connectionOptions; + private static String product; + private static String clientVersion; + + @BeforeAll + public static void init() throws Exception { + Map properties = CoreUtils.getProperties("azure-messaging-eventhubs.properties"); + product = properties.get("name"); + clientVersion = properties.get("version"); + } @BeforeEach public void setup() throws IOException { - final ConnectionHandler connectionHandler = new ConnectionHandler(CONNECTION_ID, HOSTNAME); + final ConnectionHandler connectionHandler = new ConnectionHandler(CONNECTION_ID, HOSTNAME, product, + clientVersion); MockitoAnnotations.initMocks(this); @@ -78,15 +91,17 @@ tokenCredential, CbsAuthorizationType.SHARED_ACCESS_SIGNATURE, AmqpTransportType when(reactorProvider.createReactor(connectionHandler.getConnectionId(), connectionHandler.getMaxFrameSize())) .thenReturn(reactor); - when(handlerProvider.createConnectionHandler(CONNECTION_ID, HOSTNAME, AmqpTransportType.AMQP, proxy)) + when(handlerProvider.createConnectionHandler(CONNECTION_ID, HOSTNAME, AmqpTransportType.AMQP, proxy, product, + clientVersion)) .thenReturn(connectionHandler); } @Test public void getsManagementChannel() { // Arrange - final EventHubReactorAmqpConnection connection = new EventHubReactorAmqpConnection(CONNECTION_ID, connectionOptions, - reactorProvider, handlerProvider, tokenManagerProvider, messageSerializer); + final EventHubReactorAmqpConnection connection = new EventHubReactorAmqpConnection(CONNECTION_ID, + connectionOptions, reactorProvider, handlerProvider, tokenManagerProvider, messageSerializer, product, + clientVersion); // Act & Assert StepVerifier.create(connection.getManagementNode()) diff --git a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionIntegrationTest.java b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionIntegrationTest.java index 9e38bdc0a5d11..8bf2c6c384caa 100644 --- a/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionIntegrationTest.java +++ b/sdk/eventhubs/azure-messaging-eventhubs/src/test/java/com/azure/messaging/eventhubs/implementation/ReactorConnectionIntegrationTest.java @@ -15,9 +15,12 @@ import com.azure.core.amqp.implementation.ReactorHandlerProvider; import com.azure.core.amqp.implementation.ReactorProvider; import com.azure.core.credential.TokenCredential; +import com.azure.core.util.CoreUtils; import com.azure.core.util.logging.ClientLogger; import com.azure.messaging.eventhubs.IntegrationTestBase; +import java.util.Map; import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.BeforeAll; import org.junit.jupiter.api.Test; import org.mockito.Mock; import org.mockito.MockitoAnnotations; @@ -35,11 +38,20 @@ public class ReactorConnectionIntegrationTest extends IntegrationTestBase { @Mock private MessageSerializer serializer; + private static String product; + private static String clientVersion; public ReactorConnectionIntegrationTest() { super(new ClientLogger(ReactorConnectionIntegrationTest.class)); } + @BeforeAll + public static void init() { + Map properties = CoreUtils.getProperties("azure-messaging-eventhubs.properties"); + product = properties.get("name"); + clientVersion = properties.get("version"); + } + @Override protected void beforeTest() { MockitoAnnotations.initMocks(this); @@ -58,7 +70,7 @@ protected void beforeTest() { ReactorProvider reactorProvider = new ReactorProvider(); ReactorHandlerProvider handlerProvider = new ReactorHandlerProvider(reactorProvider); connection = new ReactorConnection("test-connection-id", options, reactorProvider, - handlerProvider, tokenManagerProvider, serializer); + handlerProvider, tokenManagerProvider, serializer, product, clientVersion); } @Override diff --git a/sdk/identity/azure-identity/CHANGELOG.md b/sdk/identity/azure-identity/CHANGELOG.md index 9af926b26a3a5..275f178c9608c 100644 --- a/sdk/identity/azure-identity/CHANGELOG.md +++ b/sdk/identity/azure-identity/CHANGELOG.md @@ -1,6 +1,7 @@ # Release History -## 1.1.0-beta.1 (Unreleased) +## 1.0.2 (2020-01-07) +- Fix MSI_ENDPOINT and MSI_SECRET environment variable lookup issue in `ManagedIdentityCredential` when running on App Service ## 1.0.0 (2019-10-25) - November 2019 SDK Release **Breaking changes** diff --git a/sdk/identity/azure-identity/README.md b/sdk/identity/azure-identity/README.md index 6abb6b0469428..212d1a5e3d315 100644 --- a/sdk/identity/azure-identity/README.md +++ b/sdk/identity/azure-identity/README.md @@ -45,7 +45,7 @@ Maven dependency for Azure Secret Client library. Add it to your project's pom f com.azure azure-identity - 1.0.0 + 1.1.0-beta.1 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/identity/azure-identity/pom.xml b/sdk/identity/azure-identity/pom.xml index e6ca9c3ae917b..1adaf84fb4676 100644 --- a/sdk/identity/azure-identity/pom.xml +++ b/sdk/identity/azure-identity/pom.xml @@ -23,7 +23,7 @@ com.azure azure-core - 1.1.0 + 1.2.0 org.slf4j diff --git a/sdk/iotcentral/mgmt-v2018_09_01/pom.xml b/sdk/iotcentral/mgmt-v2018_09_01/pom.xml index b2e9bef6d1e7c..479b314aaee5a 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/pom.xml +++ b/sdk/iotcentral/mgmt-v2018_09_01/pom.xml @@ -15,11 +15,11 @@ ../../../pom.management.xml azure-mgmt-iotcentral - 1.0.0-beta + 1.0.0 jar Microsoft Azure SDK for IoTCentral Management This package contains Microsoft IoTCentral Management SDK. - https://github.com/Azure/azure-libraries-for-java + https://github.com/Azure/azure-sdk-for-java The MIT License (MIT) @@ -28,8 +28,8 @@ - scm:git:https://github.com/Azure/azure-libraries-for-java - scm:git:git@github.com:Azure/azure-libraries-for-java.git + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git HEAD @@ -71,6 +71,8 @@ azure-arm-client-runtime test-jar test + + 1.6.5 diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/App.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/App.java index f51ff4e27af1a..b36a7d0b2866e 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/App.java +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/App.java @@ -77,36 +77,44 @@ interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup, Resource.UpdateWithTags, Update */ interface UpdateStages { /** - * The stage of the app {0} allowing to specify DisplayName. + * The stage of the app update allowing to specify DisplayName. */ interface WithDisplayName { /** * Specifies displayName. + * @param displayName The display name of the application + * @return the next update stage */ Update withDisplayName(String displayName); } /** - * The stage of the app {0} allowing to specify Subdomain. + * The stage of the app update allowing to specify Subdomain. */ interface WithSubdomain { /** * Specifies subdomain. + * @param subdomain The subdomain of the application + * @return the next update stage */ Update withSubdomain(String subdomain); } /** - * The stage of the app {0} allowing to specify Template. + * The stage of the app update allowing to specify Template. */ interface WithTemplate { /** * Specifies template. + * @param template The ID of the application template, which is a blueprint that defines the characteristics and behaviors of an application. Optional; if not specified, defaults to a blank blueprint and allows the application to be defined from scratch + * @return the next update stage */ Update withTemplate(String template); } diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppNameUnavailabilityReason.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppNameUnavailabilityReason.java deleted file mode 100644 index 01ab6c857a615..0000000000000 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppNameUnavailabilityReason.java +++ /dev/null @@ -1,53 +0,0 @@ -/** - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - */ - -package com.microsoft.azure.management.iotcentral.v2018_09_01; - -import com.fasterxml.jackson.annotation.JsonCreator; -import com.fasterxml.jackson.annotation.JsonValue; - -/** - * Defines values for AppNameUnavailabilityReason. - */ -public enum AppNameUnavailabilityReason { - /** Enum value Invalid. */ - INVALID("Invalid"), - - /** Enum value AlreadyExists. */ - ALREADY_EXISTS("AlreadyExists"); - - /** The actual serialized value for a AppNameUnavailabilityReason instance. */ - private String value; - - AppNameUnavailabilityReason(String value) { - this.value = value; - } - - /** - * Parses a serialized value to a AppNameUnavailabilityReason instance. - * - * @param value the serialized value to parse. - * @return the parsed AppNameUnavailabilityReason object, or null if unable to parse. - */ - @JsonCreator - public static AppNameUnavailabilityReason fromString(String value) { - AppNameUnavailabilityReason[] items = AppNameUnavailabilityReason.values(); - for (AppNameUnavailabilityReason item : items) { - if (item.toString().equalsIgnoreCase(value)) { - return item; - } - } - return null; - } - - @JsonValue - @Override - public String toString() { - return this.value; - } -} diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppSku.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppSku.java index 7f2f66345bfb9..1ceb80cec8fa0 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppSku.java +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppSku.java @@ -22,6 +22,15 @@ public final class AppSku extends ExpandableStringEnum { /** Static value S1 for AppSku. */ public static final AppSku S1 = fromString("S1"); + /** Static value ST0 for AppSku. */ + public static final AppSku ST0 = fromString("ST0"); + + /** Static value ST1 for AppSku. */ + public static final AppSku ST1 = fromString("ST1"); + + /** Static value ST2 for AppSku. */ + public static final AppSku ST2 = fromString("ST2"); + /** * Creates or finds a AppSku from its string representation. * @param name a name to look for diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppSkuInfo.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppSkuInfo.java index 44c1c9815f706..3a501dac8a900 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppSkuInfo.java +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppSkuInfo.java @@ -15,13 +15,14 @@ */ public class AppSkuInfo { /** - * The name of the SKU. Possible values include: 'F1', 'S1'. + * The name of the SKU. Possible values include: 'F1', 'S1', 'ST0', 'ST1', + * 'ST2'. */ @JsonProperty(value = "name", required = true) private AppSku name; /** - * Get the name of the SKU. Possible values include: 'F1', 'S1'. + * Get the name of the SKU. Possible values include: 'F1', 'S1', 'ST0', 'ST1', 'ST2'. * * @return the name value */ @@ -30,7 +31,7 @@ public AppSku name() { } /** - * Set the name of the SKU. Possible values include: 'F1', 'S1'. + * Set the name of the SKU. Possible values include: 'F1', 'S1', 'ST0', 'ST1', 'ST2'. * * @param name the name value to set * @return the AppSkuInfo object itself. diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppNameAvailabilityInfo.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppTemplate.java similarity index 51% rename from sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppNameAvailabilityInfo.java rename to sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppTemplate.java index d6cf9fec610a3..274c36c81fecc 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppNameAvailabilityInfo.java +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/AppTemplate.java @@ -11,25 +11,40 @@ import com.microsoft.azure.arm.model.HasInner; import com.microsoft.azure.arm.resources.models.HasManager; import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.IoTCentralManager; -import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.AppNameAvailabilityInfoInner; +import com.microsoft.azure.management.iotcentral.v2018_09_01.implementation.AppTemplateInner; /** - * Type representing AppNameAvailabilityInfo. + * Type representing AppTemplate. */ -public interface AppNameAvailabilityInfo extends HasInner, HasManager { +public interface AppTemplate extends HasInner, HasManager { /** - * @return the message value. + * @return the appTemplateName value. */ - String message(); + String appTemplateName(); /** - * @return the nameAvailable value. + * @return the description value. */ - Boolean nameAvailable(); + String description(); /** - * @return the reason value. + * @return the manifestId value. */ - AppNameUnavailabilityReason reason(); + String manifestId(); + + /** + * @return the manifestVersion value. + */ + String manifestVersion(); + + /** + * @return the order value. + */ + Double order(); + + /** + * @return the title value. + */ + String title(); } diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/Apps.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/Apps.java index deec27d18075e..5b749808f2ff3 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/Apps.java +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/Apps.java @@ -40,4 +40,12 @@ public interface Apps extends SupportsCreating, Supp */ Observable checkSubdomainAvailabilityAsync(OperationInputs operationInputs); + /** + * Get all available application templates. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listTemplatesAsync(); + } diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/NameAvailabilityInputs.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/NameAvailabilityInputs.java deleted file mode 100644 index ae0e3c6414d0e..0000000000000 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/NameAvailabilityInputs.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - */ - -package com.microsoft.azure.management.iotcentral.v2018_09_01; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Input values. - */ -public class NameAvailabilityInputs { - /** - * The name of the IoT Central application instance to check. - */ - @JsonProperty(value = "name", required = true) - private String name; - - /** - * The type of the IoT Central resource to query. - */ - @JsonProperty(value = "type") - private String type; - - /** - * Get the name of the IoT Central application instance to check. - * - * @return the name value - */ - public String name() { - return this.name; - } - - /** - * Set the name of the IoT Central application instance to check. - * - * @param name the name value to set - * @return the NameAvailabilityInputs object itself. - */ - public NameAvailabilityInputs withName(String name) { - this.name = name; - return this; - } - - /** - * Get the type of the IoT Central resource to query. - * - * @return the type value - */ - public String type() { - return this.type; - } - - /** - * Set the type of the IoT Central resource to query. - * - * @param type the type value to set - * @return the NameAvailabilityInputs object itself. - */ - public NameAvailabilityInputs withType(String type) { - this.type = type; - return this; - } - -} diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/SubdomainAvailabilityInputs.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/SubdomainAvailabilityInputs.java deleted file mode 100644 index ad53cb471be4e..0000000000000 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/SubdomainAvailabilityInputs.java +++ /dev/null @@ -1,69 +0,0 @@ -/** - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - */ - -package com.microsoft.azure.management.iotcentral.v2018_09_01; - -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * Input values. - */ -public class SubdomainAvailabilityInputs { - /** - * The subdomain of the IoT Central application instance to check. - */ - @JsonProperty(value = "subdomain", required = true) - private String subdomain; - - /** - * The type of the IoT Central resource to query. - */ - @JsonProperty(value = "type") - private String type; - - /** - * Get the subdomain of the IoT Central application instance to check. - * - * @return the subdomain value - */ - public String subdomain() { - return this.subdomain; - } - - /** - * Set the subdomain of the IoT Central application instance to check. - * - * @param subdomain the subdomain value to set - * @return the SubdomainAvailabilityInputs object itself. - */ - public SubdomainAvailabilityInputs withSubdomain(String subdomain) { - this.subdomain = subdomain; - return this; - } - - /** - * Get the type of the IoT Central resource to query. - * - * @return the type value - */ - public String type() { - return this.type; - } - - /** - * Set the type of the IoT Central resource to query. - * - * @param type the type value to set - * @return the SubdomainAvailabilityInputs object itself. - */ - public SubdomainAvailabilityInputs withType(String type) { - this.type = type; - return this; - } - -} diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppNameAvailabilityInfoInner.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppNameAvailabilityInfoInner.java deleted file mode 100644 index cac83d5ca21fd..0000000000000 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppNameAvailabilityInfoInner.java +++ /dev/null @@ -1,76 +0,0 @@ -/** - * Copyright (c) Microsoft Corporation. All rights reserved. - * Licensed under the MIT License. See License.txt in the project root for - * license information. - * - * Code generated by Microsoft (R) AutoRest Code Generator. - */ - -package com.microsoft.azure.management.iotcentral.v2018_09_01.implementation; - -import com.microsoft.azure.management.iotcentral.v2018_09_01.AppNameUnavailabilityReason; -import com.fasterxml.jackson.annotation.JsonProperty; - -/** - * The properties indicating whether a given IoT Central application name is - * available. - */ -public class AppNameAvailabilityInfoInner { - /** - * The value which indicates whether the provided name is available. - */ - @JsonProperty(value = "nameAvailable", access = JsonProperty.Access.WRITE_ONLY) - private Boolean nameAvailable; - - /** - * The reason for unavailability. Possible values include: 'Invalid', - * 'AlreadyExists'. - */ - @JsonProperty(value = "reason", access = JsonProperty.Access.WRITE_ONLY) - private AppNameUnavailabilityReason reason; - - /** - * The detailed reason message. - */ - @JsonProperty(value = "message") - private String message; - - /** - * Get the value which indicates whether the provided name is available. - * - * @return the nameAvailable value - */ - public Boolean nameAvailable() { - return this.nameAvailable; - } - - /** - * Get the reason for unavailability. Possible values include: 'Invalid', 'AlreadyExists'. - * - * @return the reason value - */ - public AppNameUnavailabilityReason reason() { - return this.reason; - } - - /** - * Get the detailed reason message. - * - * @return the message value - */ - public String message() { - return this.message; - } - - /** - * Set the detailed reason message. - * - * @param message the message value to set - * @return the AppNameAvailabilityInfoInner object itself. - */ - public AppNameAvailabilityInfoInner withMessage(String message) { - this.message = message; - return this; - } - -} diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppNameAvailabilityInfoImpl.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppTemplateImpl.java similarity index 50% rename from sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppNameAvailabilityInfoImpl.java rename to sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppTemplateImpl.java index d68656e3d4870..c4369f12ac048 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppNameAvailabilityInfoImpl.java +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppTemplateImpl.java @@ -8,13 +8,12 @@ package com.microsoft.azure.management.iotcentral.v2018_09_01.implementation; -import com.microsoft.azure.management.iotcentral.v2018_09_01.AppNameAvailabilityInfo; +import com.microsoft.azure.management.iotcentral.v2018_09_01.AppTemplate; import com.microsoft.azure.arm.model.implementation.WrapperImpl; -import com.microsoft.azure.management.iotcentral.v2018_09_01.AppNameUnavailabilityReason; -class AppNameAvailabilityInfoImpl extends WrapperImpl implements AppNameAvailabilityInfo { +class AppTemplateImpl extends WrapperImpl implements AppTemplate { private final IoTCentralManager manager; - AppNameAvailabilityInfoImpl(AppNameAvailabilityInfoInner inner, IoTCentralManager manager) { + AppTemplateImpl(AppTemplateInner inner, IoTCentralManager manager) { super(inner); this.manager = manager; } @@ -25,18 +24,33 @@ public IoTCentralManager manager() { } @Override - public String message() { - return this.inner().message(); + public String appTemplateName() { + return this.inner().appTemplateName(); } @Override - public Boolean nameAvailable() { - return this.inner().nameAvailable(); + public String description() { + return this.inner().description(); } @Override - public AppNameUnavailabilityReason reason() { - return this.inner().reason(); + public String manifestId() { + return this.inner().manifestId(); + } + + @Override + public String manifestVersion() { + return this.inner().manifestVersion(); + } + + @Override + public Double order() { + return this.inner().order(); + } + + @Override + public String title() { + return this.inner().title(); } } diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppTemplateInner.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppTemplateInner.java new file mode 100644 index 0000000000000..c1bdc2e593e91 --- /dev/null +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppTemplateInner.java @@ -0,0 +1,107 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.iotcentral.v2018_09_01.implementation; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * IoT Central Application Template. + */ +public class AppTemplateInner { + /** + * The ID of the template. + */ + @JsonProperty(value = "manifestId", access = JsonProperty.Access.WRITE_ONLY) + private String manifestId; + + /** + * The version of the template. + */ + @JsonProperty(value = "manifestVersion", access = JsonProperty.Access.WRITE_ONLY) + private String manifestVersion; + + /** + * The name of the template. + */ + @JsonProperty(value = "appTemplateName", access = JsonProperty.Access.WRITE_ONLY) + private String appTemplateName; + + /** + * The title of the template. + */ + @JsonProperty(value = "title", access = JsonProperty.Access.WRITE_ONLY) + private String title; + + /** + * The order of the template in the templates list. + */ + @JsonProperty(value = "order", access = JsonProperty.Access.WRITE_ONLY) + private Double order; + + /** + * The description of the template. + */ + @JsonProperty(value = "description", access = JsonProperty.Access.WRITE_ONLY) + private String description; + + /** + * Get the ID of the template. + * + * @return the manifestId value + */ + public String manifestId() { + return this.manifestId; + } + + /** + * Get the version of the template. + * + * @return the manifestVersion value + */ + public String manifestVersion() { + return this.manifestVersion; + } + + /** + * Get the name of the template. + * + * @return the appTemplateName value + */ + public String appTemplateName() { + return this.appTemplateName; + } + + /** + * Get the title of the template. + * + * @return the title value + */ + public String title() { + return this.title; + } + + /** + * Get the order of the template in the templates list. + * + * @return the order value + */ + public Double order() { + return this.order; + } + + /** + * Get the description of the template. + * + * @return the description value + */ + public String description() { + return this.description; + } + +} diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppsImpl.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppsImpl.java index 537fc693efa61..f2b622a042b7b 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppsImpl.java +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppsImpl.java @@ -23,6 +23,7 @@ import com.microsoft.azure.PagedList; import com.microsoft.azure.Page; import com.microsoft.azure.management.iotcentral.v2018_09_01.AppAvailabilityInfo; +import com.microsoft.azure.management.iotcentral.v2018_09_01.AppTemplate; import com.microsoft.azure.management.iotcentral.v2018_09_01.OperationInputs; class AppsImpl extends GroupableResourcesCoreImpl implements Apps { @@ -151,6 +152,24 @@ public AppAvailabilityInfo call(AppAvailabilityInfoInner inner) { }); } + @Override + public Observable listTemplatesAsync() { + AppsInner client = this.inner(); + return client.listTemplatesAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public AppTemplate call(AppTemplateInner inner) { + return new AppTemplateImpl(inner, manager()); + } + }); + } + @Override protected AppImpl wrapModel(AppInner inner) { return new AppImpl(inner.name(), inner, manager()); diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppsInner.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppsInner.java index f551023b24b2a..2aaa8f1deacdd 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppsInner.java +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/AppsInner.java @@ -112,6 +112,10 @@ interface AppsService { @POST("subscriptions/{subscriptionId}/providers/Microsoft.IoTCentral/checkSubdomainAvailability") Observable> checkSubdomainAvailability(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Body OperationInputs operationInputs, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.iotcentral.v2018_09_01.Apps listTemplates" }) + @POST("subscriptions/{subscriptionId}/providers/Microsoft.IoTCentral/appTemplates") + Observable> listTemplates(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.iotcentral.v2018_09_01.Apps listNext" }) @GET Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); @@ -120,6 +124,10 @@ interface AppsService { @GET Observable> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.iotcentral.v2018_09_01.Apps listTemplatesNext" }) + @GET + Observable> listTemplatesNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + } /** @@ -1090,6 +1098,113 @@ private ServiceResponse checkSubdomainAvailabilityDele .build(response); } + /** + * Get all available application templates. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorDetailsException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<AppTemplateInner> object if successful. + */ + public PagedList listTemplates() { + ServiceResponse> response = listTemplatesSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listTemplatesNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Get all available application templates. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listTemplatesAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listTemplatesSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listTemplatesNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Get all available application templates. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AppTemplateInner> object + */ + public Observable> listTemplatesAsync() { + return listTemplatesWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Get all available application templates. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AppTemplateInner> object + */ + public Observable>> listTemplatesWithServiceResponseAsync() { + return listTemplatesSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listTemplatesNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Get all available application templates. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<AppTemplateInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listTemplatesSinglePageAsync() { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listTemplates(this.client.subscriptionId(), this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listTemplatesDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listTemplatesDelegate(Response response) throws ErrorDetailsException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorDetailsException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorDetailsException.class) + .build(response); + } + /** * Get all IoT Central Applications in a subscription. * @@ -1312,4 +1427,115 @@ private ServiceResponse> listByResourceGroupNextDelegate(Resp .build(response); } + /** + * Get all available application templates. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws ErrorDetailsException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<AppTemplateInner> object if successful. + */ + public PagedList listTemplatesNext(final String nextPageLink) { + ServiceResponse> response = listTemplatesNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listTemplatesNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Get all available application templates. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listTemplatesNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listTemplatesNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listTemplatesNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Get all available application templates. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AppTemplateInner> object + */ + public Observable> listTemplatesNextAsync(final String nextPageLink) { + return listTemplatesNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Get all available application templates. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<AppTemplateInner> object + */ + public Observable>> listTemplatesNextWithServiceResponseAsync(final String nextPageLink) { + return listTemplatesNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listTemplatesNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Get all available application templates. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<AppTemplateInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listTemplatesNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listTemplatesNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listTemplatesNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listTemplatesNextDelegate(Response response) throws ErrorDetailsException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorDetailsException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorDetailsException.class) + .build(response); + } + } diff --git a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/IotCentralClientImpl.java b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/IotCentralClientImpl.java index 39bad0a45afae..05afaa100cd86 100644 --- a/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/IotCentralClientImpl.java +++ b/sdk/iotcentral/mgmt-v2018_09_01/src/main/java/com/microsoft/azure/management/iotcentral/v2018_09_01/implementation/IotCentralClientImpl.java @@ -63,11 +63,11 @@ public String apiVersion() { return this.apiVersion; } - /** Gets or sets the preferred language for the response. */ + /** The preferred language for the response. */ private String acceptLanguage; /** - * Gets Gets or sets the preferred language for the response. + * Gets The preferred language for the response. * * @return the acceptLanguage value. */ @@ -76,7 +76,7 @@ public String acceptLanguage() { } /** - * Sets Gets or sets the preferred language for the response. + * Sets The preferred language for the response. * * @param acceptLanguage the acceptLanguage value. * @return the service client itself @@ -86,11 +86,11 @@ public IotCentralClientImpl withAcceptLanguage(String acceptLanguage) { return this; } - /** Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. */ + /** The retry timeout in seconds for Long Running Operations. Default value is 30. */ private int longRunningOperationRetryTimeout; /** - * Gets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. + * Gets The retry timeout in seconds for Long Running Operations. Default value is 30. * * @return the longRunningOperationRetryTimeout value. */ @@ -99,7 +99,7 @@ public int longRunningOperationRetryTimeout() { } /** - * Sets Gets or sets the retry timeout in seconds for Long Running Operations. Default value is 30. + * Sets The retry timeout in seconds for Long Running Operations. Default value is 30. * * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. * @return the service client itself @@ -109,11 +109,11 @@ public IotCentralClientImpl withLongRunningOperationRetryTimeout(int longRunning return this; } - /** When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ + /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ private boolean generateClientRequestId; /** - * Gets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @return the generateClientRequestId value. */ @@ -122,7 +122,7 @@ public boolean generateClientRequestId() { } /** - * Sets When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. * * @param generateClientRequestId the generateClientRequestId value. * @return the service client itself @@ -205,6 +205,6 @@ protected void initialize() { */ @Override public String userAgent() { - return String.format("%s (%s, %s)", super.userAgent(), "IotCentralClient", "2018-09-01"); + return String.format("%s (%s, %s, auto-generated)", super.userAgent(), "IotCentralClient", "2018-09-01"); } } diff --git a/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md index de402dedd98d4..84f65ec651d32 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-certificates/CHANGELOG.md @@ -1,6 +1,7 @@ # Release History -## 4.0.0-beta.8 (Unreleased) +## 4.0.0 (2020-01-07) +- Update azure-core dependency to version 1.2.0. ## 4.0.0-beta.7 (2019-12-17) - `beginDeleteCertificate` and `beginRecoverDeletedCertificate` methods now return a poll response with a status of SUCCESSFULLY_COMPLETED when service returns 403 status. diff --git a/sdk/keyvault/azure-security-keyvault-certificates/README.md b/sdk/keyvault/azure-security-keyvault-certificates/README.md index 805241635a582..4cc80714a7b9d 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/README.md +++ b/sdk/keyvault/azure-security-keyvault-certificates/README.md @@ -15,7 +15,7 @@ Maven dependency for Azure Key Client library. Add it to your project's pom file com.azure azure-security-keyvault-certificates - 4.0.0-beta.7 + 4.0.0 ``` [//]: # ({x-version-update-end}) @@ -34,7 +34,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-security-keyvault-certificates - 4.0.0-beta.7 + 4.0.0 com.azure @@ -50,7 +50,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-core-http-okhttp - 1.0.0 + 1.1.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/keyvault/azure-security-keyvault-certificates/pom.xml b/sdk/keyvault/azure-security-keyvault-certificates/pom.xml index 95f97d591753b..f830e3036f40c 100644 --- a/sdk/keyvault/azure-security-keyvault-certificates/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-certificates/pom.xml @@ -12,7 +12,7 @@ com.azure azure-security-keyvault-certificates - 4.0.0-beta.8 + 4.0.0 Microsoft Azure client library for KeyVault Certificates This module contains client library for Microsoft Azure KeyVault Certificates. @@ -36,13 +36,13 @@ com.azure azure-core - 1.1.0 + 1.2.0 com.azure azure-core-http-netty - 1.1.0 + 1.2.0 @@ -84,14 +84,14 @@ com.azure azure-core-test - 1.1.0-beta.1 + 1.1.0 test com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md index 7564d04158f83..ee91414750df3 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-keys/CHANGELOG.md @@ -1,6 +1,8 @@ # Release History -## 4.1.0-beta.1 (Unreleased) +## 4.1.0 (2020-01-07) +- Fixes the logic of `getKeyId()` method in `KeyEncryptionKeyClient` and `KeyEncryptionKeyAsyncClient` to ensure key id is available in all scenarios. +- Update azure-core dependency to version 1.2.0. ## 4.0.1 (2019-12-06) diff --git a/sdk/keyvault/azure-security-keyvault-keys/README.md b/sdk/keyvault/azure-security-keyvault-keys/README.md index c9e8151ffab5f..ce3eba78432c4 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/README.md +++ b/sdk/keyvault/azure-security-keyvault-keys/README.md @@ -16,7 +16,7 @@ Maven dependency for Azure Key Client library. Add it to your project's pom file com.azure azure-security-keyvault-keys - 4.0.1 + 4.1.0 ``` [//]: # ({x-version-update-end}) @@ -35,7 +35,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-security-keyvault-keys - 4.0.1 + 4.1.0 com.azure @@ -51,7 +51,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-core-http-okhttp - 1.0.0 + 1.1.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/keyvault/azure-security-keyvault-keys/pom.xml b/sdk/keyvault/azure-security-keyvault-keys/pom.xml index 07c875219e47a..1d1dcdaf42b5f 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-keys/pom.xml @@ -14,7 +14,7 @@ com.azure azure-security-keyvault-keys - 4.1.0-beta.1 + 4.1.0 Microsoft Azure client library for KeyVault Keys This module contains client library for Microsoft Azure KeyVault Keys. @@ -37,13 +37,13 @@ com.azure azure-core - 1.1.0 + 1.2.0 com.azure azure-core-http-netty - 1.1.0 + 1.2.0 @@ -82,14 +82,14 @@ com.azure azure-core-test - 1.1.0-beta.1 + 1.1.0 test com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java index 8143a33328c3b..1d93fd6bcbf65 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/CryptographyAsyncClient.java @@ -62,6 +62,7 @@ public class CryptographyAsyncClient { private LocalKeyCryptographyClient localKeyCryptographyClient; private final ClientLogger logger = new ClientLogger(CryptographyAsyncClient.class); private String keyCollection; + private final String keyId; /** * Creates a CryptographyAsyncClient that uses {@code pipeline} to service requests @@ -83,6 +84,7 @@ public class CryptographyAsyncClient { throw new IllegalArgumentException("Json Web Key's key type property is not configured"); } this.key = key; + this.keyId = key.getId(); service = RestProxy.create(CryptographyService.class, pipeline); if (!Strings.isNullOrEmpty(key.getId())) { unpackAndValidateId(key.getId()); @@ -102,6 +104,7 @@ public class CryptographyAsyncClient { */ CryptographyAsyncClient(String keyId, HttpPipeline pipeline, CryptographyServiceVersion version) { unpackAndValidateId(keyId); + this.keyId = keyId; service = RestProxy.create(CryptographyService.class, pipeline); cryptographyServiceClient = new CryptographyServiceClient(keyId, service); this.key = null; @@ -123,6 +126,10 @@ private void initializeCryptoClients() { } } + Mono getKeyId() { + return Mono.defer(() -> Mono.just(keyId)); + } + /** * Gets the public part of the configured key. The get key operation is applicable to all key types and it requires * the {@code keys/get} permission. diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyAsyncClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyAsyncClient.java index a9215929a256e..d8f25c4d32f49 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyAsyncClient.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyAsyncClient.java @@ -30,15 +30,13 @@ public final class KeyEncryptionKeyAsyncClient extends CryptographyAsyncClient i } /** - * {@inheritDoc} + * Get the identifier of the key to use for cryptography operations. + * + * @return A {@link Mono} containing the key identifier. */ @Override public Mono getKeyId() { - try { - return Mono.just(key.getId()); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } + return super.getKeyId(); } /** diff --git a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClient.java b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClient.java index 494bfad933734..0c56841b80e85 100644 --- a/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClient.java +++ b/sdk/keyvault/azure-security-keyvault-keys/src/main/java/com/azure/security/keyvault/keys/cryptography/KeyEncryptionKeyClient.java @@ -21,7 +21,9 @@ public final class KeyEncryptionKeyClient implements KeyEncryptionKey { } /** - * {@inheritDoc} + * Get the identifier of the key to use for cryptography operations. + * + * @return The key identifier. */ @Override public String getKeyId() { diff --git a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md b/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md index f50843a98aa10..fdeb031de10cc 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md +++ b/sdk/keyvault/azure-security-keyvault-secrets/CHANGELOG.md @@ -1,6 +1,8 @@ # Release History -## 4.1.0-beta.1 (Unreleased) +## 4.1.0 (2020-01-07) +- Update azure-core dependency to version 1.2.0 +- Drop commons-codec dependency ## 4.0.1 (2019-12-04) diff --git a/sdk/keyvault/azure-security-keyvault-secrets/README.md b/sdk/keyvault/azure-security-keyvault-secrets/README.md index 2602a6b88a209..4eb55cb6e3c66 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/README.md +++ b/sdk/keyvault/azure-security-keyvault-secrets/README.md @@ -17,7 +17,7 @@ Maven dependency for Azure Secret Client library. Add it to your project's pom f com.azure azure-security-keyvault-secrets - 4.0.1 + 4.1.0 ``` [//]: # ({x-version-update-end}) @@ -36,7 +36,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-security-keyvault-secrets - 4.0.1 + 4.1.0 com.azure @@ -52,7 +52,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-core-http-okhttp - 1.0.0 + 1.1.0 ``` [//]: # ({x-version-update-end}) diff --git a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml b/sdk/keyvault/azure-security-keyvault-secrets/pom.xml index 17ae014949ab6..a623bc71d3b93 100644 --- a/sdk/keyvault/azure-security-keyvault-secrets/pom.xml +++ b/sdk/keyvault/azure-security-keyvault-secrets/pom.xml @@ -11,7 +11,7 @@ com.azure azure-security-keyvault-secrets - 4.1.0-beta.1 + 4.1.0 Microsoft Azure client library for KeyVault Secrets This module contains client library for Microsoft Azure KeyVault Secrets. @@ -34,19 +34,13 @@ com.azure azure-core - 1.1.0 + 1.2.0 com.azure azure-core-http-netty - 1.1.0 - - - - commons-codec - commons-codec - 1.13 + 1.2.0 @@ -85,14 +79,14 @@ com.azure azure-core-test - 1.1.0-beta.1 + 1.1.0 test com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/mediaservices/mgmt-v2018_07_01/pom.xml b/sdk/mediaservices/mgmt-v2018_07_01/pom.xml index cdff8a07c9701..231b31643ca16 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/pom.xml +++ b/sdk/mediaservices/mgmt-v2018_07_01/pom.xml @@ -15,7 +15,7 @@ ../../../pom.management.xml azure-mgmt-media - 1.0.0-beta-4 + 1.0.0-beta-5 jar Microsoft Azure SDK for Media Management This package contains Microsoft Media Management SDK. diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/AudioAnalyzerPreset.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/AudioAnalyzerPreset.java index 43e1a5d29309f..aa4a3119e31cc 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/AudioAnalyzerPreset.java +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/AudioAnalyzerPreset.java @@ -8,6 +8,7 @@ package com.microsoft.azure.management.mediaservices.v2018_07_01; +import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; @@ -26,27 +27,30 @@ public class AudioAnalyzerPreset extends Preset { /** * The language for the audio payload in the input using the BCP-47 format - * of 'language tag-region' (e.g: 'en-US'). The list of supported - * languages are English ('en-US' and 'en-GB'), Spanish ('es-ES' and - * 'es-MX'), French ('fr-FR'), Italian ('it-IT'), Japanese ('ja-JP'), - * Portuguese ('pt-BR'), Chinese ('zh-CN'), German ('de-DE'), Arabic - * ('ar-EG' and 'ar-SY'), Russian ('ru-RU'), Hindi ('hi-IN'), and Korean - * ('ko-KR'). If you know the language of your content, it is recommended - * that you specify it. If the language isn't specified or set to null, - * automatic language detection will choose the first language detected and - * process with the selected language for the duration of the file. This - * language detection feature currently supports English, Chinese, French, - * German, Italian, Japanese, Spanish, Russian, and Portuguese. It does not - * currently support dynamically switching between languages after the - * first language is detected. The automatic detection works best with - * audio recordings with clearly discernable speech. If automatic detection - * fails to find the language, transcription would fallback to 'en-US'.". + * of 'language tag-region' (e.g: 'en-US'). If you know the language of + * your content, it is recommended that you specify it. If the language + * isn't specified or set to null, automatic language detection will choose + * the first language detected and process with the selected language for + * the duration of the file. It does not currently support dynamically + * switching between languages after the first language is detected. The + * automatic detection works best with audio recordings with clearly + * discernable speech. If automatic detection fails to find the language, + * transcription would fallback to 'en-US'." The list of supported + * languages is available here: + * https://go.microsoft.com/fwlink/?linkid=2109463. */ @JsonProperty(value = "audioLanguage") private String audioLanguage; /** - * Get the language for the audio payload in the input using the BCP-47 format of 'language tag-region' (e.g: 'en-US'). The list of supported languages are English ('en-US' and 'en-GB'), Spanish ('es-ES' and 'es-MX'), French ('fr-FR'), Italian ('it-IT'), Japanese ('ja-JP'), Portuguese ('pt-BR'), Chinese ('zh-CN'), German ('de-DE'), Arabic ('ar-EG' and 'ar-SY'), Russian ('ru-RU'), Hindi ('hi-IN'), and Korean ('ko-KR'). If you know the language of your content, it is recommended that you specify it. If the language isn't specified or set to null, automatic language detection will choose the first language detected and process with the selected language for the duration of the file. This language detection feature currently supports English, Chinese, French, German, Italian, Japanese, Spanish, Russian, and Portuguese. It does not currently support dynamically switching between languages after the first language is detected. The automatic detection works best with audio recordings with clearly discernable speech. If automatic detection fails to find the language, transcription would fallback to 'en-US'.". + * Dictionary containing key value pairs for parameters not exposed in the + * preset itself. + */ + @JsonProperty(value = "experimentalOptions") + private Map experimentalOptions; + + /** + * Get the language for the audio payload in the input using the BCP-47 format of 'language tag-region' (e.g: 'en-US'). If you know the language of your content, it is recommended that you specify it. If the language isn't specified or set to null, automatic language detection will choose the first language detected and process with the selected language for the duration of the file. It does not currently support dynamically switching between languages after the first language is detected. The automatic detection works best with audio recordings with clearly discernable speech. If automatic detection fails to find the language, transcription would fallback to 'en-US'." The list of supported languages is available here: https://go.microsoft.com/fwlink/?linkid=2109463. * * @return the audioLanguage value */ @@ -55,7 +59,7 @@ public String audioLanguage() { } /** - * Set the language for the audio payload in the input using the BCP-47 format of 'language tag-region' (e.g: 'en-US'). The list of supported languages are English ('en-US' and 'en-GB'), Spanish ('es-ES' and 'es-MX'), French ('fr-FR'), Italian ('it-IT'), Japanese ('ja-JP'), Portuguese ('pt-BR'), Chinese ('zh-CN'), German ('de-DE'), Arabic ('ar-EG' and 'ar-SY'), Russian ('ru-RU'), Hindi ('hi-IN'), and Korean ('ko-KR'). If you know the language of your content, it is recommended that you specify it. If the language isn't specified or set to null, automatic language detection will choose the first language detected and process with the selected language for the duration of the file. This language detection feature currently supports English, Chinese, French, German, Italian, Japanese, Spanish, Russian, and Portuguese. It does not currently support dynamically switching between languages after the first language is detected. The automatic detection works best with audio recordings with clearly discernable speech. If automatic detection fails to find the language, transcription would fallback to 'en-US'.". + * Set the language for the audio payload in the input using the BCP-47 format of 'language tag-region' (e.g: 'en-US'). If you know the language of your content, it is recommended that you specify it. If the language isn't specified or set to null, automatic language detection will choose the first language detected and process with the selected language for the duration of the file. It does not currently support dynamically switching between languages after the first language is detected. The automatic detection works best with audio recordings with clearly discernable speech. If automatic detection fails to find the language, transcription would fallback to 'en-US'." The list of supported languages is available here: https://go.microsoft.com/fwlink/?linkid=2109463. * * @param audioLanguage the audioLanguage value to set * @return the AudioAnalyzerPreset object itself. @@ -65,4 +69,24 @@ public AudioAnalyzerPreset withAudioLanguage(String audioLanguage) { return this; } + /** + * Get dictionary containing key value pairs for parameters not exposed in the preset itself. + * + * @return the experimentalOptions value + */ + public Map experimentalOptions() { + return this.experimentalOptions; + } + + /** + * Set dictionary containing key value pairs for parameters not exposed in the preset itself. + * + * @param experimentalOptions the experimentalOptions value to set + * @return the AudioAnalyzerPreset object itself. + */ + public AudioAnalyzerPreset withExperimentalOptions(Map experimentalOptions) { + this.experimentalOptions = experimentalOptions; + return this; + } + } diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/BuiltInStandardEncoderPreset.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/BuiltInStandardEncoderPreset.java index 7c24e1ac60370..902fe6e5dfa46 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/BuiltInStandardEncoderPreset.java +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/BuiltInStandardEncoderPreset.java @@ -23,14 +23,15 @@ public class BuiltInStandardEncoderPreset extends Preset { * The built-in preset to be used for encoding videos. Possible values * include: 'H264SingleBitrateSD', 'H264SingleBitrate720p', * 'H264SingleBitrate1080p', 'AdaptiveStreaming', 'AACGoodQualityAudio', - * 'ContentAwareEncodingExperimental', 'H264MultipleBitrate1080p', - * 'H264MultipleBitrate720p', 'H264MultipleBitrateSD'. + * 'ContentAwareEncodingExperimental', 'ContentAwareEncoding', + * 'H264MultipleBitrate1080p', 'H264MultipleBitrate720p', + * 'H264MultipleBitrateSD'. */ @JsonProperty(value = "presetName", required = true) private EncoderNamedPreset presetName; /** - * Get the built-in preset to be used for encoding videos. Possible values include: 'H264SingleBitrateSD', 'H264SingleBitrate720p', 'H264SingleBitrate1080p', 'AdaptiveStreaming', 'AACGoodQualityAudio', 'ContentAwareEncodingExperimental', 'H264MultipleBitrate1080p', 'H264MultipleBitrate720p', 'H264MultipleBitrateSD'. + * Get the built-in preset to be used for encoding videos. Possible values include: 'H264SingleBitrateSD', 'H264SingleBitrate720p', 'H264SingleBitrate1080p', 'AdaptiveStreaming', 'AACGoodQualityAudio', 'ContentAwareEncodingExperimental', 'ContentAwareEncoding', 'H264MultipleBitrate1080p', 'H264MultipleBitrate720p', 'H264MultipleBitrateSD'. * * @return the presetName value */ @@ -39,7 +40,7 @@ public EncoderNamedPreset presetName() { } /** - * Set the built-in preset to be used for encoding videos. Possible values include: 'H264SingleBitrateSD', 'H264SingleBitrate720p', 'H264SingleBitrate1080p', 'AdaptiveStreaming', 'AACGoodQualityAudio', 'ContentAwareEncodingExperimental', 'H264MultipleBitrate1080p', 'H264MultipleBitrate720p', 'H264MultipleBitrateSD'. + * Set the built-in preset to be used for encoding videos. Possible values include: 'H264SingleBitrateSD', 'H264SingleBitrate720p', 'H264SingleBitrate1080p', 'AdaptiveStreaming', 'AACGoodQualityAudio', 'ContentAwareEncodingExperimental', 'ContentAwareEncoding', 'H264MultipleBitrate1080p', 'H264MultipleBitrate720p', 'H264MultipleBitrateSD'. * * @param presetName the presetName value to set * @return the BuiltInStandardEncoderPreset object itself. diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayConfiguration.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayConfiguration.java index 83560905ff191..dd1e6da316edc 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayConfiguration.java +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayConfiguration.java @@ -39,7 +39,7 @@ public class ContentKeyPolicyFairPlayConfiguration extends ContentKeyPolicyConfi /** * The rental and lease key type. Possible values include: 'Unknown', - * 'Undefined', 'PersistentUnlimited', 'PersistentLimited'. + * 'Undefined', 'DualExpiry', 'PersistentUnlimited', 'PersistentLimited'. */ @JsonProperty(value = "rentalAndLeaseKeyType", required = true) private ContentKeyPolicyFairPlayRentalAndLeaseKeyType rentalAndLeaseKeyType; @@ -50,6 +50,12 @@ public class ContentKeyPolicyFairPlayConfiguration extends ContentKeyPolicyConfi @JsonProperty(value = "rentalDuration", required = true) private long rentalDuration; + /** + * Offline rental policy. + */ + @JsonProperty(value = "offlineRentalConfiguration") + private ContentKeyPolicyFairPlayOfflineRentalConfiguration offlineRentalConfiguration; + /** * Get the key that must be used as FairPlay Application Secret key. * @@ -111,7 +117,7 @@ public ContentKeyPolicyFairPlayConfiguration withFairPlayPfx(String fairPlayPfx) } /** - * Get the rental and lease key type. Possible values include: 'Unknown', 'Undefined', 'PersistentUnlimited', 'PersistentLimited'. + * Get the rental and lease key type. Possible values include: 'Unknown', 'Undefined', 'DualExpiry', 'PersistentUnlimited', 'PersistentLimited'. * * @return the rentalAndLeaseKeyType value */ @@ -120,7 +126,7 @@ public ContentKeyPolicyFairPlayRentalAndLeaseKeyType rentalAndLeaseKeyType() { } /** - * Set the rental and lease key type. Possible values include: 'Unknown', 'Undefined', 'PersistentUnlimited', 'PersistentLimited'. + * Set the rental and lease key type. Possible values include: 'Unknown', 'Undefined', 'DualExpiry', 'PersistentUnlimited', 'PersistentLimited'. * * @param rentalAndLeaseKeyType the rentalAndLeaseKeyType value to set * @return the ContentKeyPolicyFairPlayConfiguration object itself. @@ -150,4 +156,24 @@ public ContentKeyPolicyFairPlayConfiguration withRentalDuration(long rentalDurat return this; } + /** + * Get offline rental policy. + * + * @return the offlineRentalConfiguration value + */ + public ContentKeyPolicyFairPlayOfflineRentalConfiguration offlineRentalConfiguration() { + return this.offlineRentalConfiguration; + } + + /** + * Set offline rental policy. + * + * @param offlineRentalConfiguration the offlineRentalConfiguration value to set + * @return the ContentKeyPolicyFairPlayConfiguration object itself. + */ + public ContentKeyPolicyFairPlayConfiguration withOfflineRentalConfiguration(ContentKeyPolicyFairPlayOfflineRentalConfiguration offlineRentalConfiguration) { + this.offlineRentalConfiguration = offlineRentalConfiguration; + return this; + } + } diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayOfflineRentalConfiguration.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayOfflineRentalConfiguration.java new file mode 100644 index 0000000000000..afae16b851f7f --- /dev/null +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayOfflineRentalConfiguration.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.mediaservices.v2018_07_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The ContentKeyPolicyFairPlayOfflineRentalConfiguration model. + */ +public class ContentKeyPolicyFairPlayOfflineRentalConfiguration { + /** + * Playback duration. + */ + @JsonProperty(value = "playbackDurationSeconds", required = true) + private long playbackDurationSeconds; + + /** + * Storage duration. + */ + @JsonProperty(value = "storageDurationSeconds", required = true) + private long storageDurationSeconds; + + /** + * Get playback duration. + * + * @return the playbackDurationSeconds value + */ + public long playbackDurationSeconds() { + return this.playbackDurationSeconds; + } + + /** + * Set playback duration. + * + * @param playbackDurationSeconds the playbackDurationSeconds value to set + * @return the ContentKeyPolicyFairPlayOfflineRentalConfiguration object itself. + */ + public ContentKeyPolicyFairPlayOfflineRentalConfiguration withPlaybackDurationSeconds(long playbackDurationSeconds) { + this.playbackDurationSeconds = playbackDurationSeconds; + return this; + } + + /** + * Get storage duration. + * + * @return the storageDurationSeconds value + */ + public long storageDurationSeconds() { + return this.storageDurationSeconds; + } + + /** + * Set storage duration. + * + * @param storageDurationSeconds the storageDurationSeconds value to set + * @return the ContentKeyPolicyFairPlayOfflineRentalConfiguration object itself. + */ + public ContentKeyPolicyFairPlayOfflineRentalConfiguration withStorageDurationSeconds(long storageDurationSeconds) { + this.storageDurationSeconds = storageDurationSeconds; + return this; + } + +} diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayRentalAndLeaseKeyType.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayRentalAndLeaseKeyType.java index ec3bebb697ed6..5ac9e46af98eb 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayRentalAndLeaseKeyType.java +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/ContentKeyPolicyFairPlayRentalAndLeaseKeyType.java @@ -22,6 +22,9 @@ public final class ContentKeyPolicyFairPlayRentalAndLeaseKeyType extends Expanda /** Static value Undefined for ContentKeyPolicyFairPlayRentalAndLeaseKeyType. */ public static final ContentKeyPolicyFairPlayRentalAndLeaseKeyType UNDEFINED = fromString("Undefined"); + /** Static value DualExpiry for ContentKeyPolicyFairPlayRentalAndLeaseKeyType. */ + public static final ContentKeyPolicyFairPlayRentalAndLeaseKeyType DUAL_EXPIRY = fromString("DualExpiry"); + /** Static value PersistentUnlimited for ContentKeyPolicyFairPlayRentalAndLeaseKeyType. */ public static final ContentKeyPolicyFairPlayRentalAndLeaseKeyType PERSISTENT_UNLIMITED = fromString("PersistentUnlimited"); diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/EncoderNamedPreset.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/EncoderNamedPreset.java index 82d64dfcac5b3..a385946bf0194 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/EncoderNamedPreset.java +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/EncoderNamedPreset.java @@ -34,6 +34,9 @@ public final class EncoderNamedPreset extends ExpandableStringEnum experimentalOptions; + /** * Get specifies the maximum resolution at which your video is analyzed. The default behavior is "SourceResolution," which will keep the input video at its original resolution when analyzed. Using "StandardDefinition" will resize input videos to standard definition while preserving the appropriate aspect ratio. It will only resize if the video is of higher resolution. For example, a 1920x1080 input would be scaled to 640x360 before processing. Switching to "StandardDefinition" will reduce the time it takes to process high resolution video. It may also reduce the cost of using this component (see https://azure.microsoft.com/en-us/pricing/details/media-services/#analytics for details). However, faces that end up being too small in the resized video may not be detected. Possible values include: 'SourceResolution', 'StandardDefinition'. * @@ -57,4 +65,24 @@ public FaceDetectorPreset withResolution(AnalysisResolution resolution) { return this; } + /** + * Get dictionary containing key value pairs for parameters not exposed in the preset itself. + * + * @return the experimentalOptions value + */ + public Map experimentalOptions() { + return this.experimentalOptions; + } + + /** + * Set dictionary containing key value pairs for parameters not exposed in the preset itself. + * + * @param experimentalOptions the experimentalOptions value to set + * @return the FaceDetectorPreset object itself. + */ + public FaceDetectorPreset withExperimentalOptions(Map experimentalOptions) { + this.experimentalOptions = experimentalOptions; + return this; + } + } diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/Job.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/Job.java index 6456556e11997..01305806c5656 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/Job.java +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/Job.java @@ -40,6 +40,11 @@ public interface Job extends HasInner, Indexable, Refreshable, Up */ String description(); + /** + * @return the endTime value. + */ + DateTime endTime(); + /** * @return the id value. */ @@ -70,6 +75,11 @@ public interface Job extends HasInner, Indexable, Refreshable, Up */ Priority priority(); + /** + * @return the startTime value. + */ + DateTime startTime(); + /** * @return the state value. */ diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/JobOutput.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/JobOutput.java index 967937f1ea4ff..294843e7ef345 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/JobOutput.java +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/JobOutput.java @@ -8,6 +8,7 @@ package com.microsoft.azure.management.mediaservices.v2018_07_01; +import org.joda.time.DateTime; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonTypeInfo; import com.fasterxml.jackson.annotation.JsonTypeName; @@ -64,6 +65,18 @@ public class JobOutput { @JsonProperty(value = "label") private String label; + /** + * The UTC date and time at which this Job Output began processing. + */ + @JsonProperty(value = "startTime", access = JsonProperty.Access.WRITE_ONLY) + private DateTime startTime; + + /** + * The UTC date and time at which this Job Output finished processing. + */ + @JsonProperty(value = "endTime", access = JsonProperty.Access.WRITE_ONLY) + private DateTime endTime; + /** * Get if the JobOutput is in the Error state, it contains the details of the error. * @@ -111,4 +124,22 @@ public JobOutput withLabel(String label) { return this; } + /** + * Get the UTC date and time at which this Job Output began processing. + * + * @return the startTime value + */ + public DateTime startTime() { + return this.startTime; + } + + /** + * Get the UTC date and time at which this Job Output finished processing. + * + * @return the endTime value + */ + public DateTime endTime() { + return this.endTime; + } + } diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/JobImpl.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/JobImpl.java index 631fdc47292ea..77b9373e01e2b 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/JobImpl.java +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/JobImpl.java @@ -93,6 +93,11 @@ public String description() { return this.inner().description(); } + @Override + public DateTime endTime() { + return this.inner().endTime(); + } + @Override public String id() { return this.inner().id(); @@ -123,6 +128,11 @@ public Priority priority() { return this.inner().priority(); } + @Override + public DateTime startTime() { + return this.inner().startTime(); + } + @Override public JobState state() { return this.inner().state(); diff --git a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/JobInner.java b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/JobInner.java index 373b75be55b3b..03615f003cb51 100644 --- a/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/JobInner.java +++ b/sdk/mediaservices/mgmt-v2018_07_01/src/main/java/com/microsoft/azure/management/mediaservices/v2018_07_01/implementation/JobInner.java @@ -79,6 +79,18 @@ public class JobInner extends ProxyResource { @JsonProperty(value = "properties.correlationData") private Map correlationData; + /** + * The UTC date and time at which this Job began processing. + */ + @JsonProperty(value = "properties.startTime", access = JsonProperty.Access.WRITE_ONLY) + private DateTime startTime; + + /** + * The UTC date and time at which this Job finished processing. + */ + @JsonProperty(value = "properties.endTime", access = JsonProperty.Access.WRITE_ONLY) + private DateTime endTime; + /** * Get the UTC date and time when the Job was created, in 'YYYY-MM-DDThh:mm:ssZ' format. * @@ -206,4 +218,22 @@ public JobInner withCorrelationData(Map correlationData) { return this; } + /** + * Get the UTC date and time at which this Job began processing. + * + * @return the startTime value + */ + public DateTime startTime() { + return this.startTime; + } + + /** + * Get the UTC date and time at which this Job finished processing. + * + * @return the endTime value + */ + public DateTime endTime() { + return this.endTime; + } + } diff --git a/sdk/netapp/mgmt-v2019_10_01/pom.xml b/sdk/netapp/mgmt-v2019_10_01/pom.xml new file mode 100644 index 0000000000000..bbdb5659c8a17 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + com.microsoft.azure.netapp.v2019_10_01 + + com.microsoft.azure + azure-arm-parent + 1.2.0 + ../../../pom.management.xml + + azure-mgmt-netapp + 1.0.0-beta + jar + Microsoft Azure SDK for NetApp Management + This package contains Microsoft NetApp Management SDK. + https://github.com/Azure/azure-sdk-for-java + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + UTF-8 + + + + + microsoft + Microsoft + + + + + com.microsoft.azure + azure-client-runtime + + + com.microsoft.azure + azure-arm-client-runtime + + + junit + junit + test + + + com.microsoft.azure + azure-client-authentication + test + + + com.microsoft.azure + azure-mgmt-resources + test + + + com.microsoft.azure + azure-arm-client-runtime + test-jar + test + + 1.6.5 + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + true + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + com.microsoft.azure.management.apigeneration.LangDefinitionProcessor + + + true + true + + true + true + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.search + + + /** +
* Copyright (c) Microsoft Corporation. All rights reserved. +
* Licensed under the MIT License. See License.txt in the project root for +
* license information. +
*/ + ]]> +
+
+
+
+
+
diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Accounts.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Accounts.java new file mode 100644 index 0000000000000..9d0f4df2b7cae --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Accounts.java @@ -0,0 +1,24 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import com.microsoft.azure.arm.resources.collection.SupportsDeletingByResourceGroup; +import com.microsoft.azure.arm.resources.collection.SupportsBatchDeletion; +import com.microsoft.azure.arm.resources.collection.SupportsGettingByResourceGroup; +import rx.Observable; +import com.microsoft.azure.arm.resources.collection.SupportsListingByResourceGroup; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.AccountsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Accounts. + */ +public interface Accounts extends SupportsCreating, SupportsDeletingByResourceGroup, SupportsBatchDeletion, SupportsGettingByResourceGroup, SupportsListingByResourceGroup, HasInner { +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ActiveDirectory.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ActiveDirectory.java new file mode 100644 index 0000000000000..b686959d021b8 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ActiveDirectory.java @@ -0,0 +1,227 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Active Directory. + */ +public class ActiveDirectory { + /** + * Id of the Active Directory. + */ + @JsonProperty(value = "activeDirectoryId") + private String activeDirectoryId; + + /** + * Username of Active Directory domain administrator. + */ + @JsonProperty(value = "username") + private String username; + + /** + * Plain text password of Active Directory domain administrator. + */ + @JsonProperty(value = "password") + private String password; + + /** + * Name of the Active Directory domain. + */ + @JsonProperty(value = "domain") + private String domain; + + /** + * Comma separated list of DNS server IP addresses (IPv4 only) for the + * Active Directory domain. + */ + @JsonProperty(value = "dns") + private String dns; + + /** + * Status of the Active Directory. + */ + @JsonProperty(value = "status") + private String status; + + /** + * NetBIOS name of the SMB server. This name will be registered as a + * computer account in the AD and used to mount volumes. + */ + @JsonProperty(value = "smbServerName") + private String smbServerName; + + /** + * The Organizational Unit (OU) within the Windows Active Directory. + */ + @JsonProperty(value = "organizationalUnit") + private String organizationalUnit; + + /** + * Get id of the Active Directory. + * + * @return the activeDirectoryId value + */ + public String activeDirectoryId() { + return this.activeDirectoryId; + } + + /** + * Set id of the Active Directory. + * + * @param activeDirectoryId the activeDirectoryId value to set + * @return the ActiveDirectory object itself. + */ + public ActiveDirectory withActiveDirectoryId(String activeDirectoryId) { + this.activeDirectoryId = activeDirectoryId; + return this; + } + + /** + * Get username of Active Directory domain administrator. + * + * @return the username value + */ + public String username() { + return this.username; + } + + /** + * Set username of Active Directory domain administrator. + * + * @param username the username value to set + * @return the ActiveDirectory object itself. + */ + public ActiveDirectory withUsername(String username) { + this.username = username; + return this; + } + + /** + * Get plain text password of Active Directory domain administrator. + * + * @return the password value + */ + public String password() { + return this.password; + } + + /** + * Set plain text password of Active Directory domain administrator. + * + * @param password the password value to set + * @return the ActiveDirectory object itself. + */ + public ActiveDirectory withPassword(String password) { + this.password = password; + return this; + } + + /** + * Get name of the Active Directory domain. + * + * @return the domain value + */ + public String domain() { + return this.domain; + } + + /** + * Set name of the Active Directory domain. + * + * @param domain the domain value to set + * @return the ActiveDirectory object itself. + */ + public ActiveDirectory withDomain(String domain) { + this.domain = domain; + return this; + } + + /** + * Get comma separated list of DNS server IP addresses (IPv4 only) for the Active Directory domain. + * + * @return the dns value + */ + public String dns() { + return this.dns; + } + + /** + * Set comma separated list of DNS server IP addresses (IPv4 only) for the Active Directory domain. + * + * @param dns the dns value to set + * @return the ActiveDirectory object itself. + */ + public ActiveDirectory withDns(String dns) { + this.dns = dns; + return this; + } + + /** + * Get status of the Active Directory. + * + * @return the status value + */ + public String status() { + return this.status; + } + + /** + * Set status of the Active Directory. + * + * @param status the status value to set + * @return the ActiveDirectory object itself. + */ + public ActiveDirectory withStatus(String status) { + this.status = status; + return this; + } + + /** + * Get netBIOS name of the SMB server. This name will be registered as a computer account in the AD and used to mount volumes. + * + * @return the smbServerName value + */ + public String smbServerName() { + return this.smbServerName; + } + + /** + * Set netBIOS name of the SMB server. This name will be registered as a computer account in the AD and used to mount volumes. + * + * @param smbServerName the smbServerName value to set + * @return the ActiveDirectory object itself. + */ + public ActiveDirectory withSmbServerName(String smbServerName) { + this.smbServerName = smbServerName; + return this; + } + + /** + * Get the Organizational Unit (OU) within the Windows Active Directory. + * + * @return the organizationalUnit value + */ + public String organizationalUnit() { + return this.organizationalUnit; + } + + /** + * Set the Organizational Unit (OU) within the Windows Active Directory. + * + * @param organizationalUnit the organizationalUnit value to set + * @return the ActiveDirectory object itself. + */ + public ActiveDirectory withOrganizationalUnit(String organizationalUnit) { + this.organizationalUnit = organizationalUnit; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/AuthorizeRequest.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/AuthorizeRequest.java new file mode 100644 index 0000000000000..affc25630a40f --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/AuthorizeRequest.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Authorize request. + */ +public class AuthorizeRequest { + /** + * Resource id. + */ + @JsonProperty(value = "remoteVolumeResourceId") + private String remoteVolumeResourceId; + + /** + * Get resource id. + * + * @return the remoteVolumeResourceId value + */ + public String remoteVolumeResourceId() { + return this.remoteVolumeResourceId; + } + + /** + * Set resource id. + * + * @param remoteVolumeResourceId the remoteVolumeResourceId value to set + * @return the AuthorizeRequest object itself. + */ + public AuthorizeRequest withRemoteVolumeResourceId(String remoteVolumeResourceId) { + this.remoteVolumeResourceId = remoteVolumeResourceId; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/CapacityPool.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/CapacityPool.java new file mode 100644 index 0000000000000..472d3fc0a6d74 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/CapacityPool.java @@ -0,0 +1,203 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.CapacityPoolInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppManager; +import java.util.Map; + +/** + * Type representing CapacityPool. + */ +public interface CapacityPool extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the poolId value. + */ + String poolId(); + + /** + * @return the provisioningState value. + */ + String provisioningState(); + + /** + * @return the serviceLevel value. + */ + ServiceLevel serviceLevel(); + + /** + * @return the size value. + */ + long size(); + + /** + * @return the tags value. + */ + Map tags(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the CapacityPool definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithNetAppAccount, DefinitionStages.WithLocation, DefinitionStages.WithServiceLevel, DefinitionStages.WithSize, DefinitionStages.WithCreate { + } + + /** + * Grouping of CapacityPool definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a CapacityPool definition. + */ + interface Blank extends WithNetAppAccount { + } + + /** + * The stage of the capacitypool definition allowing to specify NetAppAccount. + */ + interface WithNetAppAccount { + /** + * Specifies resourceGroupName, accountName. + * @param resourceGroupName The name of the resource group + * @param accountName The name of the NetApp account + * @return the next definition stage + */ + WithLocation withExistingNetAppAccount(String resourceGroupName, String accountName); + } + + /** + * The stage of the capacitypool definition allowing to specify Location. + */ + interface WithLocation { + /** + * Specifies location. + * @param location the location parameter value + * @return the next definition stage + */ + WithServiceLevel withLocation(String location); + } + + /** + * The stage of the capacitypool definition allowing to specify ServiceLevel. + */ + interface WithServiceLevel { + /** + * Specifies serviceLevel. + * @param serviceLevel The service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra' + * @return the next definition stage + */ + WithSize withServiceLevel(ServiceLevel serviceLevel); + } + + /** + * The stage of the capacitypool definition allowing to specify Size. + */ + interface WithSize { + /** + * Specifies size. + * @param size Provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104) + * @return the next definition stage + */ + WithCreate withSize(long size); + } + + /** + * The stage of the capacitypool definition allowing to specify Tags. + */ + interface WithTags { + /** + * Specifies tags. + * @param tags the tags parameter value + * @return the next definition stage + */ + WithCreate withTags(Map tags); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable, DefinitionStages.WithTags { + } + } + /** + * The template for a CapacityPool update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithServiceLevel, UpdateStages.WithSize, UpdateStages.WithTags { + } + + /** + * Grouping of CapacityPool update stages. + */ + interface UpdateStages { + /** + * The stage of the capacitypool update allowing to specify ServiceLevel. + */ + interface WithServiceLevel { + /** + * Specifies serviceLevel. + * @param serviceLevel The service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra' + * @return the next update stage + */ + Update withServiceLevel(ServiceLevel serviceLevel); + } + + /** + * The stage of the capacitypool update allowing to specify Size. + */ + interface WithSize { + /** + * Specifies size. + * @param size Provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104) + * @return the next update stage + */ + Update withSize(Long size); + } + + /** + * The stage of the capacitypool update allowing to specify Tags. + */ + interface WithTags { + /** + * Specifies tags. + * @param tags the tags parameter value + * @return the next update stage + */ + Update withTags(Map tags); + } + + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/CapacityPoolPatch.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/CapacityPoolPatch.java new file mode 100644 index 0000000000000..36a61278cd2dd --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/CapacityPoolPatch.java @@ -0,0 +1,76 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.Resource; + +/** + * Capacity pool patch resource. + */ +@JsonFlatten +public class CapacityPoolPatch extends Resource { + /** + * size. + * Provisioned size of the pool (in bytes). Allowed values are in 4TiB + * chunks (value must be multiply of 4398046511104). + */ + @JsonProperty(value = "properties.size") + private Long size; + + /** + * serviceLevel. + * The service level of the file system. Possible values include: + * 'Standard', 'Premium', 'Ultra'. + */ + @JsonProperty(value = "properties.serviceLevel") + private ServiceLevel serviceLevel; + + /** + * Get provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104). + * + * @return the size value + */ + public Long size() { + return this.size; + } + + /** + * Set provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104). + * + * @param size the size value to set + * @return the CapacityPoolPatch object itself. + */ + public CapacityPoolPatch withSize(Long size) { + this.size = size; + return this; + } + + /** + * Get the service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra'. + * + * @return the serviceLevel value + */ + public ServiceLevel serviceLevel() { + return this.serviceLevel; + } + + /** + * Set the service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra'. + * + * @param serviceLevel the serviceLevel value to set + * @return the CapacityPoolPatch object itself. + */ + public CapacityPoolPatch withServiceLevel(ServiceLevel serviceLevel) { + this.serviceLevel = serviceLevel; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/CheckNameResourceTypes.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/CheckNameResourceTypes.java new file mode 100644 index 0000000000000..bd9d9ad7b226f --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/CheckNameResourceTypes.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for CheckNameResourceTypes. + */ +public final class CheckNameResourceTypes extends ExpandableStringEnum { + /** Static value Microsoft.NetApp/netAppAccounts for CheckNameResourceTypes. */ + public static final CheckNameResourceTypes MICROSOFT_NET_APPNET_APP_ACCOUNTS = fromString("Microsoft.NetApp/netAppAccounts"); + + /** Static value Microsoft.NetApp/netAppAccounts/capacityPools for CheckNameResourceTypes. */ + public static final CheckNameResourceTypes MICROSOFT_NET_APPNET_APP_ACCOUNTSCAPACITY_POOLS = fromString("Microsoft.NetApp/netAppAccounts/capacityPools"); + + /** Static value Microsoft.NetApp/netAppAccounts/capacityPools/volumes for CheckNameResourceTypes. */ + public static final CheckNameResourceTypes MICROSOFT_NET_APPNET_APP_ACCOUNTSCAPACITY_POOLSVOLUMES = fromString("Microsoft.NetApp/netAppAccounts/capacityPools/volumes"); + + /** Static value Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots for CheckNameResourceTypes. */ + public static final CheckNameResourceTypes MICROSOFT_NET_APPNET_APP_ACCOUNTSCAPACITY_POOLSVOLUMESSNAPSHOTS = fromString("Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots"); + + /** + * Creates or finds a CheckNameResourceTypes from its string representation. + * @param name a name to look for + * @return the corresponding CheckNameResourceTypes + */ + @JsonCreator + public static CheckNameResourceTypes fromString(String name) { + return fromString(name, CheckNameResourceTypes.class); + } + + /** + * @return known CheckNameResourceTypes values + */ + public static Collection values() { + return values(CheckNameResourceTypes.class); + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Dimension.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Dimension.java new file mode 100644 index 0000000000000..2734033114fb6 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Dimension.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Dimension of blobs, possibly be blob type or access tier. + */ +public class Dimension { + /** + * Display name of dimension. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Display name of dimension. + */ + @JsonProperty(value = "displayName") + private String displayName; + + /** + * Get display name of dimension. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set display name of dimension. + * + * @param name the name value to set + * @return the Dimension object itself. + */ + public Dimension withName(String name) { + this.name = name; + return this; + } + + /** + * Get display name of dimension. + * + * @return the displayName value + */ + public String displayName() { + return this.displayName; + } + + /** + * Set display name of dimension. + * + * @param displayName the displayName value to set + * @return the Dimension object itself. + */ + public Dimension withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/EndpointType.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/EndpointType.java new file mode 100644 index 0000000000000..b52f57b9a9ef5 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/EndpointType.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for EndpointType. + */ +public final class EndpointType extends ExpandableStringEnum { + /** Static value src for EndpointType. */ + public static final EndpointType SRC = fromString("src"); + + /** Static value dst for EndpointType. */ + public static final EndpointType DST = fromString("dst"); + + /** + * Creates or finds a EndpointType from its string representation. + * @param name a name to look for + * @return the corresponding EndpointType + */ + @JsonCreator + public static EndpointType fromString(String name) { + return fromString(name, EndpointType.class); + } + + /** + * @return known EndpointType values + */ + public static Collection values() { + return values(EndpointType.class); + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ExportPolicyRule.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ExportPolicyRule.java new file mode 100644 index 0000000000000..c0b05158e3a40 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ExportPolicyRule.java @@ -0,0 +1,200 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Volume Export Policy Rule. + */ +public class ExportPolicyRule { + /** + * Order index. + */ + @JsonProperty(value = "ruleIndex") + private Integer ruleIndex; + + /** + * Read only access. + */ + @JsonProperty(value = "unixReadOnly") + private Boolean unixReadOnly; + + /** + * Read and write access. + */ + @JsonProperty(value = "unixReadWrite") + private Boolean unixReadWrite; + + /** + * Allows CIFS protocol. + */ + @JsonProperty(value = "cifs") + private Boolean cifs; + + /** + * Allows NFSv3 protocol. + */ + @JsonProperty(value = "nfsv3") + private Boolean nfsv3; + + /** + * Allows NFSv4.1 protocol. + */ + @JsonProperty(value = "nfsv41") + private Boolean nfsv41; + + /** + * Client ingress specification as comma separated string with IPv4 CIDRs, + * IPv4 host addresses and host names. + */ + @JsonProperty(value = "allowedClients") + private String allowedClients; + + /** + * Get order index. + * + * @return the ruleIndex value + */ + public Integer ruleIndex() { + return this.ruleIndex; + } + + /** + * Set order index. + * + * @param ruleIndex the ruleIndex value to set + * @return the ExportPolicyRule object itself. + */ + public ExportPolicyRule withRuleIndex(Integer ruleIndex) { + this.ruleIndex = ruleIndex; + return this; + } + + /** + * Get read only access. + * + * @return the unixReadOnly value + */ + public Boolean unixReadOnly() { + return this.unixReadOnly; + } + + /** + * Set read only access. + * + * @param unixReadOnly the unixReadOnly value to set + * @return the ExportPolicyRule object itself. + */ + public ExportPolicyRule withUnixReadOnly(Boolean unixReadOnly) { + this.unixReadOnly = unixReadOnly; + return this; + } + + /** + * Get read and write access. + * + * @return the unixReadWrite value + */ + public Boolean unixReadWrite() { + return this.unixReadWrite; + } + + /** + * Set read and write access. + * + * @param unixReadWrite the unixReadWrite value to set + * @return the ExportPolicyRule object itself. + */ + public ExportPolicyRule withUnixReadWrite(Boolean unixReadWrite) { + this.unixReadWrite = unixReadWrite; + return this; + } + + /** + * Get allows CIFS protocol. + * + * @return the cifs value + */ + public Boolean cifs() { + return this.cifs; + } + + /** + * Set allows CIFS protocol. + * + * @param cifs the cifs value to set + * @return the ExportPolicyRule object itself. + */ + public ExportPolicyRule withCifs(Boolean cifs) { + this.cifs = cifs; + return this; + } + + /** + * Get allows NFSv3 protocol. + * + * @return the nfsv3 value + */ + public Boolean nfsv3() { + return this.nfsv3; + } + + /** + * Set allows NFSv3 protocol. + * + * @param nfsv3 the nfsv3 value to set + * @return the ExportPolicyRule object itself. + */ + public ExportPolicyRule withNfsv3(Boolean nfsv3) { + this.nfsv3 = nfsv3; + return this; + } + + /** + * Get allows NFSv4.1 protocol. + * + * @return the nfsv41 value + */ + public Boolean nfsv41() { + return this.nfsv41; + } + + /** + * Set allows NFSv4.1 protocol. + * + * @param nfsv41 the nfsv41 value to set + * @return the ExportPolicyRule object itself. + */ + public ExportPolicyRule withNfsv41(Boolean nfsv41) { + this.nfsv41 = nfsv41; + return this; + } + + /** + * Get client ingress specification as comma separated string with IPv4 CIDRs, IPv4 host addresses and host names. + * + * @return the allowedClients value + */ + public String allowedClients() { + return this.allowedClients; + } + + /** + * Set client ingress specification as comma separated string with IPv4 CIDRs, IPv4 host addresses and host names. + * + * @param allowedClients the allowedClients value to set + * @return the ExportPolicyRule object itself. + */ + public ExportPolicyRule withAllowedClients(String allowedClients) { + this.allowedClients = allowedClients; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/InAvailabilityReasonType.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/InAvailabilityReasonType.java new file mode 100644 index 0000000000000..895f0232907f9 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/InAvailabilityReasonType.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for InAvailabilityReasonType. + */ +public final class InAvailabilityReasonType extends ExpandableStringEnum { + /** Static value Invalid for InAvailabilityReasonType. */ + public static final InAvailabilityReasonType INVALID = fromString("Invalid"); + + /** Static value AlreadyExists for InAvailabilityReasonType. */ + public static final InAvailabilityReasonType ALREADY_EXISTS = fromString("AlreadyExists"); + + /** + * Creates or finds a InAvailabilityReasonType from its string representation. + * @param name a name to look for + * @return the corresponding InAvailabilityReasonType + */ + @JsonCreator + public static InAvailabilityReasonType fromString(String name) { + return fromString(name, InAvailabilityReasonType.class); + } + + /** + * @return known InAvailabilityReasonType values + */ + public static Collection values() { + return values(InAvailabilityReasonType.class); + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MetricSpecification.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MetricSpecification.java new file mode 100644 index 0000000000000..4109b2dc3cc88 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MetricSpecification.java @@ -0,0 +1,252 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Metric specification of operation. + */ +public class MetricSpecification { + /** + * Name of metric specification. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Display name of metric specification. + */ + @JsonProperty(value = "displayName") + private String displayName; + + /** + * Display description of metric specification. + */ + @JsonProperty(value = "displayDescription") + private String displayDescription; + + /** + * Unit could be Bytes or Count. + */ + @JsonProperty(value = "unit") + private String unit; + + /** + * Dimensions of blobs, including blob type and access tier. + */ + @JsonProperty(value = "dimensions") + private List dimensions; + + /** + * Aggregation type could be Average. + */ + @JsonProperty(value = "aggregationType") + private String aggregationType; + + /** + * The property to decide fill gap with zero or not. + */ + @JsonProperty(value = "fillGapWithZero") + private Boolean fillGapWithZero; + + /** + * The category this metric specification belong to, could be Capacity. + */ + @JsonProperty(value = "category") + private String category; + + /** + * Account Resource Id. + */ + @JsonProperty(value = "resourceIdDimensionNameOverride") + private String resourceIdDimensionNameOverride; + + /** + * Get name of metric specification. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set name of metric specification. + * + * @param name the name value to set + * @return the MetricSpecification object itself. + */ + public MetricSpecification withName(String name) { + this.name = name; + return this; + } + + /** + * Get display name of metric specification. + * + * @return the displayName value + */ + public String displayName() { + return this.displayName; + } + + /** + * Set display name of metric specification. + * + * @param displayName the displayName value to set + * @return the MetricSpecification object itself. + */ + public MetricSpecification withDisplayName(String displayName) { + this.displayName = displayName; + return this; + } + + /** + * Get display description of metric specification. + * + * @return the displayDescription value + */ + public String displayDescription() { + return this.displayDescription; + } + + /** + * Set display description of metric specification. + * + * @param displayDescription the displayDescription value to set + * @return the MetricSpecification object itself. + */ + public MetricSpecification withDisplayDescription(String displayDescription) { + this.displayDescription = displayDescription; + return this; + } + + /** + * Get unit could be Bytes or Count. + * + * @return the unit value + */ + public String unit() { + return this.unit; + } + + /** + * Set unit could be Bytes or Count. + * + * @param unit the unit value to set + * @return the MetricSpecification object itself. + */ + public MetricSpecification withUnit(String unit) { + this.unit = unit; + return this; + } + + /** + * Get dimensions of blobs, including blob type and access tier. + * + * @return the dimensions value + */ + public List dimensions() { + return this.dimensions; + } + + /** + * Set dimensions of blobs, including blob type and access tier. + * + * @param dimensions the dimensions value to set + * @return the MetricSpecification object itself. + */ + public MetricSpecification withDimensions(List dimensions) { + this.dimensions = dimensions; + return this; + } + + /** + * Get aggregation type could be Average. + * + * @return the aggregationType value + */ + public String aggregationType() { + return this.aggregationType; + } + + /** + * Set aggregation type could be Average. + * + * @param aggregationType the aggregationType value to set + * @return the MetricSpecification object itself. + */ + public MetricSpecification withAggregationType(String aggregationType) { + this.aggregationType = aggregationType; + return this; + } + + /** + * Get the property to decide fill gap with zero or not. + * + * @return the fillGapWithZero value + */ + public Boolean fillGapWithZero() { + return this.fillGapWithZero; + } + + /** + * Set the property to decide fill gap with zero or not. + * + * @param fillGapWithZero the fillGapWithZero value to set + * @return the MetricSpecification object itself. + */ + public MetricSpecification withFillGapWithZero(Boolean fillGapWithZero) { + this.fillGapWithZero = fillGapWithZero; + return this; + } + + /** + * Get the category this metric specification belong to, could be Capacity. + * + * @return the category value + */ + public String category() { + return this.category; + } + + /** + * Set the category this metric specification belong to, could be Capacity. + * + * @param category the category value to set + * @return the MetricSpecification object itself. + */ + public MetricSpecification withCategory(String category) { + this.category = category; + return this; + } + + /** + * Get account Resource Id. + * + * @return the resourceIdDimensionNameOverride value + */ + public String resourceIdDimensionNameOverride() { + return this.resourceIdDimensionNameOverride; + } + + /** + * Set account Resource Id. + * + * @param resourceIdDimensionNameOverride the resourceIdDimensionNameOverride value to set + * @return the MetricSpecification object itself. + */ + public MetricSpecification withResourceIdDimensionNameOverride(String resourceIdDimensionNameOverride) { + this.resourceIdDimensionNameOverride = resourceIdDimensionNameOverride; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MirrorState.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MirrorState.java new file mode 100644 index 0000000000000..c63bbb36a140f --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MirrorState.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for MirrorState. + */ +public final class MirrorState extends ExpandableStringEnum { + /** Static value Uninitialized for MirrorState. */ + public static final MirrorState UNINITIALIZED = fromString("Uninitialized"); + + /** Static value Mirrored for MirrorState. */ + public static final MirrorState MIRRORED = fromString("Mirrored"); + + /** Static value Broken for MirrorState. */ + public static final MirrorState BROKEN = fromString("Broken"); + + /** + * Creates or finds a MirrorState from its string representation. + * @param name a name to look for + * @return the corresponding MirrorState + */ + @JsonCreator + public static MirrorState fromString(String name) { + return fromString(name, MirrorState.class); + } + + /** + * @return known MirrorState values + */ + public static Collection values() { + return values(MirrorState.class); + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MountTarget.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MountTarget.java new file mode 100644 index 0000000000000..34cb0d820ad50 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MountTarget.java @@ -0,0 +1,96 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.MountTargetInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppManager; +import java.util.Map; + +/** + * Type representing MountTarget. + */ +public interface MountTarget extends HasInner, HasManager { + /** + * @return the endIp value. + */ + String endIp(); + + /** + * @return the fileSystemId value. + */ + String fileSystemId(); + + /** + * @return the gateway value. + */ + String gateway(); + + /** + * @return the id value. + */ + String id(); + + /** + * @return the ipAddress value. + */ + String ipAddress(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the mountTargetId value. + */ + String mountTargetId(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the netmask value. + */ + String netmask(); + + /** + * @return the provisioningState value. + */ + String provisioningState(); + + /** + * @return the smbServerFqdn value. + */ + String smbServerFqdn(); + + /** + * @return the startIp value. + */ + String startIp(); + + /** + * @return the subnet value. + */ + String subnet(); + + /** + * @return the tags value. + */ + Map tags(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MountTargets.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MountTargets.java new file mode 100644 index 0000000000000..9e8cbafb10417 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/MountTargets.java @@ -0,0 +1,32 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.MountTargetsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing MountTargets. + */ +public interface MountTargets extends HasInner { + /** + * Describe all mount targets. + * List all mount targets associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + Observable listAsync(String resourceGroupName, String accountName, String poolName, String volumeName); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/NetAppAccount.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/NetAppAccount.java new file mode 100644 index 0000000000000..143913a9d91f5 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/NetAppAccount.java @@ -0,0 +1,103 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.Resource; +import com.microsoft.azure.arm.resources.models.GroupableResourceCore; +import com.microsoft.azure.arm.resources.models.HasResourceGroup; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppManager; +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppAccountInner; + +/** + * Type representing NetAppAccount. + */ +public interface NetAppAccount extends HasInner, Resource, GroupableResourceCore, HasResourceGroup, Refreshable, Updatable, HasManager { + /** + * @return the activeDirectories value. + */ + List activeDirectories(); + + /** + * @return the provisioningState value. + */ + String provisioningState(); + + /** + * The entirety of the NetAppAccount definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithGroup, DefinitionStages.WithCreate { + } + + /** + * Grouping of NetAppAccount definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a NetAppAccount definition. + */ + interface Blank extends GroupableResourceCore.DefinitionWithRegion { + } + + /** + * The stage of the NetAppAccount definition allowing to specify the resource group. + */ + interface WithGroup extends GroupableResourceCore.DefinitionStages.WithGroup { + } + + /** + * The stage of the netappaccount definition allowing to specify ActiveDirectories. + */ + interface WithActiveDirectories { + /** + * Specifies activeDirectories. + * @param activeDirectories Active Directories + * @return the next definition stage + */ + WithCreate withActiveDirectories(List activeDirectories); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable, Resource.DefinitionWithTags, DefinitionStages.WithActiveDirectories { + } + } + /** + * The template for a NetAppAccount update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, Resource.UpdateWithTags, UpdateStages.WithActiveDirectories { + } + + /** + * Grouping of NetAppAccount update stages. + */ + interface UpdateStages { + /** + * The stage of the netappaccount update allowing to specify ActiveDirectories. + */ + interface WithActiveDirectories { + /** + * Specifies activeDirectories. + * @param activeDirectories Active Directories + * @return the next update stage + */ + Update withActiveDirectories(List activeDirectories); + } + + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/NetAppAccountPatch.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/NetAppAccountPatch.java new file mode 100644 index 0000000000000..48701b8863a62 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/NetAppAccountPatch.java @@ -0,0 +1,62 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.Resource; + +/** + * NetApp account patch resource. + */ +@JsonFlatten +public class NetAppAccountPatch extends Resource { + /** + * Azure lifecycle management. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * Active Directories. + */ + @JsonProperty(value = "properties.activeDirectories") + private List activeDirectories; + + /** + * Get azure lifecycle management. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + + /** + * Get active Directories. + * + * @return the activeDirectories value + */ + public List activeDirectories() { + return this.activeDirectories; + } + + /** + * Set active Directories. + * + * @param activeDirectories the activeDirectories value to set + * @return the NetAppAccountPatch object itself. + */ + public NetAppAccountPatch withActiveDirectories(List activeDirectories) { + this.activeDirectories = activeDirectories; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/NetAppResources.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/NetAppResources.java new file mode 100644 index 0000000000000..f0e92898f5db2 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/NetAppResources.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppResourcesInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing NetAppResources. + */ +public interface NetAppResources extends HasInner { + /** + * Check resource name availability. + * Check if a resource name is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable checkNameAvailabilityAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup); + + /** + * Check file path availability. + * Check if a file path is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable checkFilePathAvailabilityAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Operation.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Operation.java new file mode 100644 index 0000000000000..748fde47e72fc --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Operation.java @@ -0,0 +1,40 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.OperationInner; + +/** + * Type representing Operation. + */ +public interface Operation extends HasInner, HasManager { + /** + * @return the display value. + */ + OperationDisplay display(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the origin value. + */ + String origin(); + + /** + * @return the serviceSpecification value. + */ + ServiceSpecification serviceSpecification(); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/OperationDisplay.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/OperationDisplay.java new file mode 100644 index 0000000000000..f317a8d023d97 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/OperationDisplay.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Display metadata associated with the operation. + */ +public class OperationDisplay { + /** + * Service provider: Microsoft NetApp. + */ + @JsonProperty(value = "provider") + private String provider; + + /** + * Resource on which the operation is performed etc. + */ + @JsonProperty(value = "resource") + private String resource; + + /** + * Type of operation: get, read, delete, etc. + */ + @JsonProperty(value = "operation") + private String operation; + + /** + * Operation description. + */ + @JsonProperty(value = "description") + private String description; + + /** + * Get service provider: Microsoft NetApp. + * + * @return the provider value + */ + public String provider() { + return this.provider; + } + + /** + * Set service provider: Microsoft NetApp. + * + * @param provider the provider value to set + * @return the OperationDisplay object itself. + */ + public OperationDisplay withProvider(String provider) { + this.provider = provider; + return this; + } + + /** + * Get resource on which the operation is performed etc. + * + * @return the resource value + */ + public String resource() { + return this.resource; + } + + /** + * Set resource on which the operation is performed etc. + * + * @param resource the resource value to set + * @return the OperationDisplay object itself. + */ + public OperationDisplay withResource(String resource) { + this.resource = resource; + return this; + } + + /** + * Get type of operation: get, read, delete, etc. + * + * @return the operation value + */ + public String operation() { + return this.operation; + } + + /** + * Set type of operation: get, read, delete, etc. + * + * @param operation the operation value to set + * @return the OperationDisplay object itself. + */ + public OperationDisplay withOperation(String operation) { + this.operation = operation; + return this; + } + + /** + * Get operation description. + * + * @return the description value + */ + public String description() { + return this.description; + } + + /** + * Set operation description. + * + * @param description the description value to set + * @return the OperationDisplay object itself. + */ + public OperationDisplay withDescription(String description) { + this.description = description; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Operations.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Operations.java new file mode 100644 index 0000000000000..f924852959fd4 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Operations.java @@ -0,0 +1,28 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.OperationsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Operations. + */ +public interface Operations extends HasInner { + /** + * Describes the Resource Provider. + * Lists all of the available Microsoft.NetApp Rest API operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Pools.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Pools.java new file mode 100644 index 0000000000000..3ca768a00b575 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Pools.java @@ -0,0 +1,56 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.PoolsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Pools. + */ +public interface Pools extends SupportsCreating, HasInner { + /** + * Describe a Capacity Pool. + * Get details of the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String resourceGroupName, String accountName, String poolName); + + /** + * Describe all Capacity Pools. + * List all capacity pools in the NetApp Account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(String resourceGroupName, String accountName); + + /** + * Delete a capacity pool. + * Delete the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String resourceGroupName, String accountName, String poolName); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/RelationshipStatus.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/RelationshipStatus.java new file mode 100644 index 0000000000000..887d23eec9f16 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/RelationshipStatus.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for RelationshipStatus. + */ +public final class RelationshipStatus extends ExpandableStringEnum { + /** Static value Idle for RelationshipStatus. */ + public static final RelationshipStatus IDLE = fromString("Idle"); + + /** Static value Transferring for RelationshipStatus. */ + public static final RelationshipStatus TRANSFERRING = fromString("Transferring"); + + /** + * Creates or finds a RelationshipStatus from its string representation. + * @param name a name to look for + * @return the corresponding RelationshipStatus + */ + @JsonCreator + public static RelationshipStatus fromString(String name) { + return fromString(name, RelationshipStatus.class); + } + + /** + * @return known RelationshipStatus values + */ + public static Collection values() { + return values(RelationshipStatus.class); + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ReplicationObject.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ReplicationObject.java new file mode 100644 index 0000000000000..c605dd9e91b44 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ReplicationObject.java @@ -0,0 +1,149 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Replication properties. + */ +public class ReplicationObject { + /** + * Id. + */ + @JsonProperty(value = "replicationId") + private String replicationId; + + /** + * Indicates whether the local volume is the source or destination for the + * Volume Replication. Possible values include: 'src', 'dst'. + */ + @JsonProperty(value = "endpointType") + private EndpointType endpointType; + + /** + * Schedule. Possible values include: '_10minutely', 'hourly', 'daily', + * 'weekly', 'monthly'. + */ + @JsonProperty(value = "replicationSchedule", required = true) + private ReplicationSchedule replicationSchedule; + + /** + * The resource ID of the remote volume. + */ + @JsonProperty(value = "remoteVolumeResourceId", required = true) + private String remoteVolumeResourceId; + + /** + * The remote region for the other end of the Volume Replication. + */ + @JsonProperty(value = "remoteVolumeRegion") + private String remoteVolumeRegion; + + /** + * Get id. + * + * @return the replicationId value + */ + public String replicationId() { + return this.replicationId; + } + + /** + * Set id. + * + * @param replicationId the replicationId value to set + * @return the ReplicationObject object itself. + */ + public ReplicationObject withReplicationId(String replicationId) { + this.replicationId = replicationId; + return this; + } + + /** + * Get indicates whether the local volume is the source or destination for the Volume Replication. Possible values include: 'src', 'dst'. + * + * @return the endpointType value + */ + public EndpointType endpointType() { + return this.endpointType; + } + + /** + * Set indicates whether the local volume is the source or destination for the Volume Replication. Possible values include: 'src', 'dst'. + * + * @param endpointType the endpointType value to set + * @return the ReplicationObject object itself. + */ + public ReplicationObject withEndpointType(EndpointType endpointType) { + this.endpointType = endpointType; + return this; + } + + /** + * Get schedule. Possible values include: '_10minutely', 'hourly', 'daily', 'weekly', 'monthly'. + * + * @return the replicationSchedule value + */ + public ReplicationSchedule replicationSchedule() { + return this.replicationSchedule; + } + + /** + * Set schedule. Possible values include: '_10minutely', 'hourly', 'daily', 'weekly', 'monthly'. + * + * @param replicationSchedule the replicationSchedule value to set + * @return the ReplicationObject object itself. + */ + public ReplicationObject withReplicationSchedule(ReplicationSchedule replicationSchedule) { + this.replicationSchedule = replicationSchedule; + return this; + } + + /** + * Get the resource ID of the remote volume. + * + * @return the remoteVolumeResourceId value + */ + public String remoteVolumeResourceId() { + return this.remoteVolumeResourceId; + } + + /** + * Set the resource ID of the remote volume. + * + * @param remoteVolumeResourceId the remoteVolumeResourceId value to set + * @return the ReplicationObject object itself. + */ + public ReplicationObject withRemoteVolumeResourceId(String remoteVolumeResourceId) { + this.remoteVolumeResourceId = remoteVolumeResourceId; + return this; + } + + /** + * Get the remote region for the other end of the Volume Replication. + * + * @return the remoteVolumeRegion value + */ + public String remoteVolumeRegion() { + return this.remoteVolumeRegion; + } + + /** + * Set the remote region for the other end of the Volume Replication. + * + * @param remoteVolumeRegion the remoteVolumeRegion value to set + * @return the ReplicationObject object itself. + */ + public ReplicationObject withRemoteVolumeRegion(String remoteVolumeRegion) { + this.remoteVolumeRegion = remoteVolumeRegion; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ReplicationSchedule.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ReplicationSchedule.java new file mode 100644 index 0000000000000..58329e33bfa36 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ReplicationSchedule.java @@ -0,0 +1,50 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for ReplicationSchedule. + */ +public final class ReplicationSchedule extends ExpandableStringEnum { + /** Static value _10minutely for ReplicationSchedule. */ + public static final ReplicationSchedule _10MINUTELY = fromString("_10minutely"); + + /** Static value hourly for ReplicationSchedule. */ + public static final ReplicationSchedule HOURLY = fromString("hourly"); + + /** Static value daily for ReplicationSchedule. */ + public static final ReplicationSchedule DAILY = fromString("daily"); + + /** Static value weekly for ReplicationSchedule. */ + public static final ReplicationSchedule WEEKLY = fromString("weekly"); + + /** Static value monthly for ReplicationSchedule. */ + public static final ReplicationSchedule MONTHLY = fromString("monthly"); + + /** + * Creates or finds a ReplicationSchedule from its string representation. + * @param name a name to look for + * @return the corresponding ReplicationSchedule + */ + @JsonCreator + public static ReplicationSchedule fromString(String name) { + return fromString(name, ReplicationSchedule.class); + } + + /** + * @return known ReplicationSchedule values + */ + public static Collection values() { + return values(ReplicationSchedule.class); + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ReplicationStatus.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ReplicationStatus.java new file mode 100644 index 0000000000000..f869df5b55411 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ReplicationStatus.java @@ -0,0 +1,45 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.ReplicationStatusInner; + +/** + * Type representing ReplicationStatus. + */ +public interface ReplicationStatus extends HasInner, HasManager { + /** + * @return the errorMessage value. + */ + String errorMessage(); + + /** + * @return the healthy value. + */ + Boolean healthy(); + + /** + * @return the mirrorState value. + */ + MirrorState mirrorState(); + + /** + * @return the relationshipStatus value. + */ + RelationshipStatus relationshipStatus(); + + /** + * @return the totalProgress value. + */ + String totalProgress(); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ResourceNameAvailability.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ResourceNameAvailability.java new file mode 100644 index 0000000000000..1fa0289a97e3d --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ResourceNameAvailability.java @@ -0,0 +1,35 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.ResourceNameAvailabilityInner; + +/** + * Type representing ResourceNameAvailability. + */ +public interface ResourceNameAvailability extends HasInner, HasManager { + /** + * @return the isAvailable value. + */ + Boolean isAvailable(); + + /** + * @return the message value. + */ + String message(); + + /** + * @return the reason value. + */ + InAvailabilityReasonType reason(); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ResourceNameAvailabilityRequest.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ResourceNameAvailabilityRequest.java new file mode 100644 index 0000000000000..48d2638750fe2 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ResourceNameAvailabilityRequest.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Resource name availability request content. + */ +public class ResourceNameAvailabilityRequest { + /** + * Resource name to verify. + */ + @JsonProperty(value = "name", required = true) + private String name; + + /** + * Resource type used for verification. Possible values include: + * 'Microsoft.NetApp/netAppAccounts', + * 'Microsoft.NetApp/netAppAccounts/capacityPools', + * 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', + * 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'. + */ + @JsonProperty(value = "type", required = true) + private CheckNameResourceTypes type; + + /** + * Resource group name. + */ + @JsonProperty(value = "resourceGroup", required = true) + private String resourceGroup; + + /** + * Get resource name to verify. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set resource name to verify. + * + * @param name the name value to set + * @return the ResourceNameAvailabilityRequest object itself. + */ + public ResourceNameAvailabilityRequest withName(String name) { + this.name = name; + return this; + } + + /** + * Get resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'. + * + * @return the type value + */ + public CheckNameResourceTypes type() { + return this.type; + } + + /** + * Set resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots'. + * + * @param type the type value to set + * @return the ResourceNameAvailabilityRequest object itself. + */ + public ResourceNameAvailabilityRequest withType(CheckNameResourceTypes type) { + this.type = type; + return this; + } + + /** + * Get resource group name. + * + * @return the resourceGroup value + */ + public String resourceGroup() { + return this.resourceGroup; + } + + /** + * Set resource group name. + * + * @param resourceGroup the resourceGroup value to set + * @return the ResourceNameAvailabilityRequest object itself. + */ + public ResourceNameAvailabilityRequest withResourceGroup(String resourceGroup) { + this.resourceGroup = resourceGroup; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ServiceLevel.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ServiceLevel.java new file mode 100644 index 0000000000000..61b09c33ab903 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ServiceLevel.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for ServiceLevel. + */ +public final class ServiceLevel extends ExpandableStringEnum { + /** Static value Standard for ServiceLevel. */ + public static final ServiceLevel STANDARD = fromString("Standard"); + + /** Static value Premium for ServiceLevel. */ + public static final ServiceLevel PREMIUM = fromString("Premium"); + + /** Static value Ultra for ServiceLevel. */ + public static final ServiceLevel ULTRA = fromString("Ultra"); + + /** + * Creates or finds a ServiceLevel from its string representation. + * @param name a name to look for + * @return the corresponding ServiceLevel + */ + @JsonCreator + public static ServiceLevel fromString(String name) { + return fromString(name, ServiceLevel.class); + } + + /** + * @return known ServiceLevel values + */ + public static Collection values() { + return values(ServiceLevel.class); + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ServiceSpecification.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ServiceSpecification.java new file mode 100644 index 0000000000000..21c8e4f35f0fb --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/ServiceSpecification.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * One property of operation, include metric specifications. + */ +public class ServiceSpecification { + /** + * Metric specifications of operation. + */ + @JsonProperty(value = "metricSpecifications") + private List metricSpecifications; + + /** + * Get metric specifications of operation. + * + * @return the metricSpecifications value + */ + public List metricSpecifications() { + return this.metricSpecifications; + } + + /** + * Set metric specifications of operation. + * + * @param metricSpecifications the metricSpecifications value to set + * @return the ServiceSpecification object itself. + */ + public ServiceSpecification withMetricSpecifications(List metricSpecifications) { + this.metricSpecifications = metricSpecifications; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Snapshot.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Snapshot.java new file mode 100644 index 0000000000000..4b17b13597261 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Snapshot.java @@ -0,0 +1,182 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.SnapshotInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppManager; +import org.joda.time.DateTime; +import java.util.Map; + +/** + * Type representing Snapshot. + */ +public interface Snapshot extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the created value. + */ + DateTime created(); + + /** + * @return the fileSystemId value. + */ + String fileSystemId(); + + /** + * @return the id value. + */ + String id(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the provisioningState value. + */ + String provisioningState(); + + /** + * @return the snapshotId value. + */ + String snapshotId(); + + /** + * @return the tags value. + */ + Map tags(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the Snapshot definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithVolume, DefinitionStages.WithLocation, DefinitionStages.WithCreate { + } + + /** + * Grouping of Snapshot definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a Snapshot definition. + */ + interface Blank extends WithVolume { + } + + /** + * The stage of the snapshot definition allowing to specify Volume. + */ + interface WithVolume { + /** + * Specifies resourceGroupName, accountName, poolName, volumeName. + * @param resourceGroupName The name of the resource group + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @return the next definition stage + */ + WithLocation withExistingVolume(String resourceGroupName, String accountName, String poolName, String volumeName); + } + + /** + * The stage of the snapshot definition allowing to specify Location. + */ + interface WithLocation { + /** + * Specifies location. + * @param location the location parameter value + * @return the next definition stage + */ + WithCreate withLocation(String location); + } + + /** + * The stage of the snapshot definition allowing to specify FileSystemId. + */ + interface WithFileSystemId { + /** + * Specifies fileSystemId. + * @param fileSystemId UUID v4 used to identify the FileSystem + * @return the next definition stage + */ + WithCreate withFileSystemId(String fileSystemId); + } + + /** + * The stage of the snapshot definition allowing to specify Tags. + */ + interface WithTags { + /** + * Specifies tags. + * @param tags the tags parameter value + * @return the next definition stage + */ + WithCreate withTags(Map tags); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable, DefinitionStages.WithFileSystemId, DefinitionStages.WithTags { + } + } + /** + * The template for a Snapshot update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithFileSystemId, UpdateStages.WithTags { + } + + /** + * Grouping of Snapshot update stages. + */ + interface UpdateStages { + /** + * The stage of the snapshot update allowing to specify FileSystemId. + */ + interface WithFileSystemId { + /** + * Specifies fileSystemId. + * @param fileSystemId UUID v4 used to identify the FileSystem + * @return the next update stage + */ + Update withFileSystemId(String fileSystemId); + } + + /** + * The stage of the snapshot update allowing to specify Tags. + */ + interface WithTags { + /** + * Specifies tags. + * @param tags the tags parameter value + * @return the next update stage + */ + Update withTags(Map tags); + } + + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/SnapshotPatch.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/SnapshotPatch.java new file mode 100644 index 0000000000000..de78a3dcb6d36 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/SnapshotPatch.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Snapshot patch. + */ +public class SnapshotPatch { + /** + * Resource tags. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * Get resource tags. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set resource tags. + * + * @param tags the tags value to set + * @return the SnapshotPatch object itself. + */ + public SnapshotPatch withTags(Map tags) { + this.tags = tags; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Snapshots.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Snapshots.java new file mode 100644 index 0000000000000..c7ed4ce1b7212 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Snapshots.java @@ -0,0 +1,62 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.SnapshotsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Snapshots. + */ +public interface Snapshots extends SupportsCreating, HasInner { + /** + * Describe a snapshot. + * Get details of the specified snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName); + + /** + * Describe all snapshots. + * List all snapshots associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + Observable listAsync(String resourceGroupName, String accountName, String poolName, String volumeName); + + /** + * Delete a snapshot. + * Delete snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Completable deleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Volume.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Volume.java new file mode 100644 index 0000000000000..0dd2324cab024 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Volume.java @@ -0,0 +1,375 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.VolumeInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Refreshable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.NetAppManager; +import java.util.List; +import java.util.Map; + +/** + * Type representing Volume. + */ +public interface Volume extends HasInner, Indexable, Refreshable, Updatable, HasManager { + /** + * @return the baremetalTenantId value. + */ + String baremetalTenantId(); + + /** + * @return the creationToken value. + */ + String creationToken(); + + /** + * @return the dataProtection value. + */ + VolumePropertiesDataProtection dataProtection(); + + /** + * @return the exportPolicy value. + */ + VolumePropertiesExportPolicy exportPolicy(); + + /** + * @return the fileSystemId value. + */ + String fileSystemId(); + + /** + * @return the id value. + */ + String id(); + + /** + * @return the isRestoring value. + */ + Boolean isRestoring(); + + /** + * @return the location value. + */ + String location(); + + /** + * @return the mountTargets value. + */ + Object mountTargets(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the protocolTypes value. + */ + List protocolTypes(); + + /** + * @return the provisioningState value. + */ + String provisioningState(); + + /** + * @return the serviceLevel value. + */ + ServiceLevel serviceLevel(); + + /** + * @return the snapshotId value. + */ + String snapshotId(); + + /** + * @return the subnetId value. + */ + String subnetId(); + + /** + * @return the tags value. + */ + Map tags(); + + /** + * @return the type value. + */ + String type(); + + /** + * @return the usageThreshold value. + */ + long usageThreshold(); + + /** + * @return the volumeType value. + */ + String volumeType(); + + /** + * The entirety of the Volume definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithCapacityPool, DefinitionStages.WithCreationToken, DefinitionStages.WithLocation, DefinitionStages.WithSubnetId, DefinitionStages.WithUsageThreshold, DefinitionStages.WithCreate { + } + + /** + * Grouping of Volume definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a Volume definition. + */ + interface Blank extends WithCapacityPool { + } + + /** + * The stage of the volume definition allowing to specify CapacityPool. + */ + interface WithCapacityPool { + /** + * Specifies resourceGroupName, accountName, poolName. + * @param resourceGroupName The name of the resource group + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @return the next definition stage + */ + WithCreationToken withExistingCapacityPool(String resourceGroupName, String accountName, String poolName); + } + + /** + * The stage of the volume definition allowing to specify CreationToken. + */ + interface WithCreationToken { + /** + * Specifies creationToken. + * @param creationToken A unique file path for the volume. Used when creating mount targets + * @return the next definition stage + */ + WithLocation withCreationToken(String creationToken); + } + + /** + * The stage of the volume definition allowing to specify Location. + */ + interface WithLocation { + /** + * Specifies location. + * @param location the location parameter value + * @return the next definition stage + */ + WithSubnetId withLocation(String location); + } + + /** + * The stage of the volume definition allowing to specify SubnetId. + */ + interface WithSubnetId { + /** + * Specifies subnetId. + * @param subnetId The Azure Resource URI for a delegated subnet. Must have the delegation Microsoft.NetApp/volumes + * @return the next definition stage + */ + WithUsageThreshold withSubnetId(String subnetId); + } + + /** + * The stage of the volume definition allowing to specify UsageThreshold. + */ + interface WithUsageThreshold { + /** + * Specifies usageThreshold. + * @param usageThreshold Maximum storage quota allowed for a file system in bytes. This is a soft quota used for alerting only. Minimum size is 100 GiB. Upper limit is 100TiB. Specified in bytes + * @return the next definition stage + */ + WithCreate withUsageThreshold(long usageThreshold); + } + + /** + * The stage of the volume definition allowing to specify DataProtection. + */ + interface WithDataProtection { + /** + * Specifies dataProtection. + * @param dataProtection DataProtection type volumes include an object containing details of the replication + * @return the next definition stage + */ + WithCreate withDataProtection(VolumePropertiesDataProtection dataProtection); + } + + /** + * The stage of the volume definition allowing to specify ExportPolicy. + */ + interface WithExportPolicy { + /** + * Specifies exportPolicy. + * @param exportPolicy Set of export policy rules + * @return the next definition stage + */ + WithCreate withExportPolicy(VolumePropertiesExportPolicy exportPolicy); + } + + /** + * The stage of the volume definition allowing to specify IsRestoring. + */ + interface WithIsRestoring { + /** + * Specifies isRestoring. + * @param isRestoring Restoring + * @return the next definition stage + */ + WithCreate withIsRestoring(Boolean isRestoring); + } + + /** + * The stage of the volume definition allowing to specify MountTargets. + */ + interface WithMountTargets { + /** + * Specifies mountTargets. + * @param mountTargets List of mount targets + * @return the next definition stage + */ + WithCreate withMountTargets(Object mountTargets); + } + + /** + * The stage of the volume definition allowing to specify ProtocolTypes. + */ + interface WithProtocolTypes { + /** + * Specifies protocolTypes. + * @param protocolTypes Set of protocol types + * @return the next definition stage + */ + WithCreate withProtocolTypes(List protocolTypes); + } + + /** + * The stage of the volume definition allowing to specify ServiceLevel. + */ + interface WithServiceLevel { + /** + * Specifies serviceLevel. + * @param serviceLevel The service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra' + * @return the next definition stage + */ + WithCreate withServiceLevel(ServiceLevel serviceLevel); + } + + /** + * The stage of the volume definition allowing to specify SnapshotId. + */ + interface WithSnapshotId { + /** + * Specifies snapshotId. + * @param snapshotId UUID v4 or resource identifier used to identify the Snapshot + * @return the next definition stage + */ + WithCreate withSnapshotId(String snapshotId); + } + + /** + * The stage of the volume definition allowing to specify Tags. + */ + interface WithTags { + /** + * Specifies tags. + * @param tags the tags parameter value + * @return the next definition stage + */ + WithCreate withTags(Map tags); + } + + /** + * The stage of the volume definition allowing to specify VolumeType. + */ + interface WithVolumeType { + /** + * Specifies volumeType. + * @param volumeType What type of volume is this + * @return the next definition stage + */ + WithCreate withVolumeType(String volumeType); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable, DefinitionStages.WithDataProtection, DefinitionStages.WithExportPolicy, DefinitionStages.WithIsRestoring, DefinitionStages.WithMountTargets, DefinitionStages.WithProtocolTypes, DefinitionStages.WithServiceLevel, DefinitionStages.WithSnapshotId, DefinitionStages.WithTags, DefinitionStages.WithVolumeType { + } + } + /** + * The template for a Volume update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithExportPolicy, UpdateStages.WithServiceLevel, UpdateStages.WithTags, UpdateStages.WithUsageThreshold { + } + + /** + * Grouping of Volume update stages. + */ + interface UpdateStages { + /** + * The stage of the volume update allowing to specify ExportPolicy. + */ + interface WithExportPolicy { + /** + * Specifies exportPolicy. + * @param exportPolicy Set of export policy rules + * @return the next update stage + */ + Update withExportPolicy(VolumePatchPropertiesExportPolicy exportPolicy); + } + + /** + * The stage of the volume update allowing to specify ServiceLevel. + */ + interface WithServiceLevel { + /** + * Specifies serviceLevel. + * @param serviceLevel The service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra' + * @return the next update stage + */ + Update withServiceLevel(ServiceLevel serviceLevel); + } + + /** + * The stage of the volume update allowing to specify Tags. + */ + interface WithTags { + /** + * Specifies tags. + * @param tags the tags parameter value + * @return the next update stage + */ + Update withTags(Map tags); + } + + /** + * The stage of the volume update allowing to specify UsageThreshold. + */ + interface WithUsageThreshold { + /** + * Specifies usageThreshold. + * @param usageThreshold Maximum storage quota allowed for a file system in bytes. This is a soft quota used for alerting only. Minimum size is 100 GiB. Upper limit is 100TiB. Specified in bytes + * @return the next update stage + */ + Update withUsageThreshold(Long usageThreshold); + } + + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePatch.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePatch.java new file mode 100644 index 0000000000000..e945e5b7cd679 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePatch.java @@ -0,0 +1,104 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.Resource; + +/** + * Volume patch resource. + */ +@JsonFlatten +public class VolumePatch extends Resource { + /** + * serviceLevel. + * The service level of the file system. Possible values include: + * 'Standard', 'Premium', 'Ultra'. + */ + @JsonProperty(value = "properties.serviceLevel") + private ServiceLevel serviceLevel; + + /** + * usageThreshold. + * Maximum storage quota allowed for a file system in bytes. This is a soft + * quota used for alerting only. Minimum size is 100 GiB. Upper limit is + * 100TiB. Specified in bytes. + */ + @JsonProperty(value = "properties.usageThreshold") + private Long usageThreshold; + + /** + * exportPolicy. + * Set of export policy rules. + */ + @JsonProperty(value = "properties.exportPolicy") + private VolumePatchPropertiesExportPolicy exportPolicy; + + /** + * Get the service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra'. + * + * @return the serviceLevel value + */ + public ServiceLevel serviceLevel() { + return this.serviceLevel; + } + + /** + * Set the service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra'. + * + * @param serviceLevel the serviceLevel value to set + * @return the VolumePatch object itself. + */ + public VolumePatch withServiceLevel(ServiceLevel serviceLevel) { + this.serviceLevel = serviceLevel; + return this; + } + + /** + * Get maximum storage quota allowed for a file system in bytes. This is a soft quota used for alerting only. Minimum size is 100 GiB. Upper limit is 100TiB. Specified in bytes. + * + * @return the usageThreshold value + */ + public Long usageThreshold() { + return this.usageThreshold; + } + + /** + * Set maximum storage quota allowed for a file system in bytes. This is a soft quota used for alerting only. Minimum size is 100 GiB. Upper limit is 100TiB. Specified in bytes. + * + * @param usageThreshold the usageThreshold value to set + * @return the VolumePatch object itself. + */ + public VolumePatch withUsageThreshold(Long usageThreshold) { + this.usageThreshold = usageThreshold; + return this; + } + + /** + * Get set of export policy rules. + * + * @return the exportPolicy value + */ + public VolumePatchPropertiesExportPolicy exportPolicy() { + return this.exportPolicy; + } + + /** + * Set set of export policy rules. + * + * @param exportPolicy the exportPolicy value to set + * @return the VolumePatch object itself. + */ + public VolumePatch withExportPolicy(VolumePatchPropertiesExportPolicy exportPolicy) { + this.exportPolicy = exportPolicy; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePatchPropertiesExportPolicy.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePatchPropertiesExportPolicy.java new file mode 100644 index 0000000000000..ee4590984f856 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePatchPropertiesExportPolicy.java @@ -0,0 +1,46 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * exportPolicy. + * Set of export policy rules. + */ +public class VolumePatchPropertiesExportPolicy { + /** + * Export policy rule. + * Export policy rule. + */ + @JsonProperty(value = "rules") + private List rules; + + /** + * Get export policy rule. + * + * @return the rules value + */ + public List rules() { + return this.rules; + } + + /** + * Set export policy rule. + * + * @param rules the rules value to set + * @return the VolumePatchPropertiesExportPolicy object itself. + */ + public VolumePatchPropertiesExportPolicy withRules(List rules) { + this.rules = rules; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePropertiesDataProtection.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePropertiesDataProtection.java new file mode 100644 index 0000000000000..ae6057c1edc0d --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePropertiesDataProtection.java @@ -0,0 +1,46 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * DataProtection. + * DataProtection type volumes include an object containing details of the + * replication. + */ +public class VolumePropertiesDataProtection { + /** + * Replication. + * Replication properties. + */ + @JsonProperty(value = "replication") + private ReplicationObject replication; + + /** + * Get replication properties. + * + * @return the replication value + */ + public ReplicationObject replication() { + return this.replication; + } + + /** + * Set replication properties. + * + * @param replication the replication value to set + * @return the VolumePropertiesDataProtection object itself. + */ + public VolumePropertiesDataProtection withReplication(ReplicationObject replication) { + this.replication = replication; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePropertiesExportPolicy.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePropertiesExportPolicy.java new file mode 100644 index 0000000000000..f6a240f12e249 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/VolumePropertiesExportPolicy.java @@ -0,0 +1,46 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * exportPolicy. + * Set of export policy rules. + */ +public class VolumePropertiesExportPolicy { + /** + * Export policy rule. + * Export policy rule. + */ + @JsonProperty(value = "rules") + private List rules; + + /** + * Get export policy rule. + * + * @return the rules value + */ + public List rules() { + return this.rules; + } + + /** + * Set export policy rule. + * + * @param rules the rules value to set + * @return the VolumePropertiesExportPolicy object itself. + */ + public VolumePropertiesExportPolicy withRules(List rules) { + this.rules = rules; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Volumes.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Volumes.java new file mode 100644 index 0000000000000..30573d9b866cd --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/Volumes.java @@ -0,0 +1,124 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.implementation.VolumesInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Volumes. + */ +public interface Volumes extends SupportsCreating, HasInner { + /** + * Break volume replication. + * Break the replication connection on the destination volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + Completable breakReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName); + + /** + * Resync volume replication. + * Resync the connection on the destination volume. If the operation is ran on the source volume it will reverse-resync the connection and sync from source to destination. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + Completable resyncReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName); + + /** + * Delete volume replication. + * Delete the replication connection on the destination volume, and send release to the source replication. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + Completable deleteReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName); + + /** + * Authorize source volume replication. + * Authorize the replication connection on the source volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + Completable authorizeReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName); + + /** + * Describe a volume. + * Get the details of the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + Observable getAsync(String resourceGroupName, String accountName, String poolName, String volumeName); + + /** + * Describe all volumes. + * List all volumes within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(String resourceGroupName, String accountName, String poolName); + + /** + * Delete a volume. + * Delete the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + Completable deleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName); + + /** + * Get volume replication status. + * Get the status of the replication. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + Observable replicationStatusMethodAsync(String resourceGroupName, String accountName, String poolName, String volumeName); + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/AccountsImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/AccountsImpl.java new file mode 100644 index 0000000000000..fde618e6971a4 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/AccountsImpl.java @@ -0,0 +1,114 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * def + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.arm.resources.collection.implementation.GroupableResourcesCoreImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.Accounts; +import com.microsoft.azure.management.netapp.v2019_10_01.NetAppAccount; +import rx.Observable; +import rx.Completable; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import com.microsoft.azure.arm.resources.ResourceUtilsCore; +import com.microsoft.azure.arm.utils.RXMapper; +import rx.functions.Func1; +import com.microsoft.azure.PagedList; +import com.microsoft.azure.Page; + +class AccountsImpl extends GroupableResourcesCoreImpl implements Accounts { + protected AccountsImpl(NetAppManager manager) { + super(manager.inner().accounts(), manager); + } + + @Override + protected Observable getInnerAsync(String resourceGroupName, String name) { + AccountsInner client = this.inner(); + return client.getByResourceGroupAsync(resourceGroupName, name); + } + + @Override + protected Completable deleteInnerAsync(String resourceGroupName, String name) { + AccountsInner client = this.inner(); + return client.deleteAsync(resourceGroupName, name).toCompletable(); + } + + @Override + public Observable deleteByIdsAsync(Collection ids) { + if (ids == null || ids.isEmpty()) { + return Observable.empty(); + } + Collection> observables = new ArrayList<>(); + for (String id : ids) { + final String resourceGroupName = ResourceUtilsCore.groupFromResourceId(id); + final String name = ResourceUtilsCore.nameFromResourceId(id); + Observable o = RXMapper.map(this.inner().deleteAsync(resourceGroupName, name), id); + observables.add(o); + } + return Observable.mergeDelayError(observables); + } + + @Override + public Observable deleteByIdsAsync(String...ids) { + return this.deleteByIdsAsync(new ArrayList(Arrays.asList(ids))); + } + + @Override + public void deleteByIds(Collection ids) { + if (ids != null && !ids.isEmpty()) { + this.deleteByIdsAsync(ids).toBlocking().last(); + } + } + + @Override + public void deleteByIds(String...ids) { + this.deleteByIds(new ArrayList(Arrays.asList(ids))); + } + + @Override + public PagedList listByResourceGroup(String resourceGroupName) { + AccountsInner client = this.inner(); + return this.wrapList(client.listByResourceGroup(resourceGroupName)); + } + + @Override + public Observable listByResourceGroupAsync(String resourceGroupName) { + AccountsInner client = this.inner(); + return client.listByResourceGroupAsync(resourceGroupName) + .flatMap(new Func1, Observable>() { + @Override + public Observable call(Page innerPage) { + return Observable.from(innerPage.items()); + } + }) + .map(new Func1() { + @Override + public NetAppAccount call(NetAppAccountInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public NetAppAccountImpl define(String name) { + return wrapModel(name); + } + + @Override + protected NetAppAccountImpl wrapModel(NetAppAccountInner inner) { + return new NetAppAccountImpl(inner.name(), inner, manager()); + } + + @Override + protected NetAppAccountImpl wrapModel(String name) { + return new NetAppAccountImpl(name, new NetAppAccountInner(), this.manager()); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/AccountsInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/AccountsInner.java new file mode 100644 index 0000000000000..d86eedb2153fd --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/AccountsInner.java @@ -0,0 +1,719 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.arm.collection.InnerSupportsGet; +import com.microsoft.azure.arm.collection.InnerSupportsDelete; +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.management.netapp.v2019_10_01.NetAppAccountPatch; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Accounts. + */ +public class AccountsInner implements InnerSupportsGet, InnerSupportsDelete { + /** The Retrofit service to perform REST calls. */ + private AccountsService service; + /** The service client containing this operation class. */ + private AzureNetAppFilesManagementClientImpl client; + + /** + * Initializes an instance of AccountsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public AccountsInner(Retrofit retrofit, AzureNetAppFilesManagementClientImpl client) { + this.service = retrofit.create(AccountsService.class); + this.client = client; + } + + /** + * The interface defining all the services for Accounts to be + * used by Retrofit to perform actually REST calls. + */ + interface AccountsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Accounts listByResourceGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts") + Observable> listByResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Accounts getByResourceGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}") + Observable> getByResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Accounts createOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}") + Observable> createOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Body NetAppAccountInner body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Accounts beginCreateOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}") + Observable> beginCreateOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Body NetAppAccountInner body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Accounts delete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Accounts beginDelete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Accounts update" }) + @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}") + Observable> update(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Body NetAppAccountPatch body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Describe all NetApp Accounts in a resource group. + * List and describe all NetApp accounts in the resource group. + * + * @param resourceGroupName The name of the resource group. + * @return the PagedList object if successful. + */ + public PagedList listByResourceGroup(String resourceGroupName) { + PageImpl page = new PageImpl<>(); + page.setItems(listByResourceGroupWithServiceResponseAsync(resourceGroupName).toBlocking().single().body()); + page.setNextPageLink(null); + return new PagedList(page) { + @Override + public Page nextPage(String nextPageLink) { + return null; + } + }; + } + + /** + * Describe all NetApp Accounts in a resource group. + * List and describe all NetApp accounts in the resource group. + * + * @param resourceGroupName The name of the resource group. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupAsync(String resourceGroupName, final ServiceCallback> serviceCallback) { + return ServiceFuture.fromResponse(listByResourceGroupWithServiceResponseAsync(resourceGroupName), serviceCallback); + } + + /** + * Describe all NetApp Accounts in a resource group. + * List and describe all NetApp accounts in the resource group. + * + * @param resourceGroupName The name of the resource group. + * @return the observable to the List<NetAppAccountInner> object + */ + public Observable> listByResourceGroupAsync(String resourceGroupName) { + return listByResourceGroupWithServiceResponseAsync(resourceGroupName).map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + PageImpl page = new PageImpl<>(); + page.setItems(response.body()); + return page; + } + }); + } + + /** + * Describe all NetApp Accounts in a resource group. + * List and describe all NetApp accounts in the resource group. + * + * @param resourceGroupName The name of the resource group. + * @return the observable to the List<NetAppAccountInner> object + */ + public Observable>> listByResourceGroupWithServiceResponseAsync(String resourceGroupName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.listByResourceGroup(this.client.subscriptionId(), resourceGroupName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupDelegate(response); + List items = null; + if (result.body() != null) { + items = result.body().items(); + } + ServiceResponse> clientResponse = new ServiceResponse>(items, result.response()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByResourceGroupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Describe a NetApp Account. + * Get the NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetAppAccountInner object if successful. + */ + public NetAppAccountInner getByResourceGroup(String resourceGroupName, String accountName) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body(); + } + + /** + * Describe a NetApp Account. + * Get the NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getByResourceGroupAsync(String resourceGroupName, String accountName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(resourceGroupName, accountName), serviceCallback); + } + + /** + * Describe a NetApp Account. + * Get the NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetAppAccountInner object + */ + public Observable getByResourceGroupAsync(String resourceGroupName, String accountName) { + return getByResourceGroupWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1, NetAppAccountInner>() { + @Override + public NetAppAccountInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Describe a NetApp Account. + * Get the NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetAppAccountInner object + */ + public Observable> getByResourceGroupWithServiceResponseAsync(String resourceGroupName, String accountName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.getByResourceGroup(this.client.subscriptionId(), resourceGroupName, accountName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getByResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getByResourceGroupDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Create or update a NetApp account. + * Create or update the specified NetApp account within the resource group. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetAppAccountInner object if successful. + */ + public NetAppAccountInner createOrUpdate(String resourceGroupName, String accountName, NetAppAccountInner body) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, body).toBlocking().last().body(); + } + + /** + * Create or update a NetApp account. + * Create or update the specified NetApp account within the resource group. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAsync(String resourceGroupName, String accountName, NetAppAccountInner body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, body), serviceCallback); + } + + /** + * Create or update a NetApp account. + * Create or update the specified NetApp account within the resource group. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createOrUpdateAsync(String resourceGroupName, String accountName, NetAppAccountInner body) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, body).map(new Func1, NetAppAccountInner>() { + @Override + public NetAppAccountInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create or update a NetApp account. + * Create or update the specified NetApp account within the resource group. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String accountName, NetAppAccountInner body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + Observable> observable = service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, accountName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Create or update a NetApp account. + * Create or update the specified NetApp account within the resource group. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetAppAccountInner object if successful. + */ + public NetAppAccountInner beginCreateOrUpdate(String resourceGroupName, String accountName, NetAppAccountInner body) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, body).toBlocking().single().body(); + } + + /** + * Create or update a NetApp account. + * Create or update the specified NetApp account within the resource group. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateOrUpdateAsync(String resourceGroupName, String accountName, NetAppAccountInner body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, body), serviceCallback); + } + + /** + * Create or update a NetApp account. + * Create or update the specified NetApp account within the resource group. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetAppAccountInner object + */ + public Observable beginCreateOrUpdateAsync(String resourceGroupName, String accountName, NetAppAccountInner body) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, body).map(new Func1, NetAppAccountInner>() { + @Override + public NetAppAccountInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create or update a NetApp account. + * Create or update the specified NetApp account within the resource group. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetAppAccountInner object + */ + public Observable> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String accountName, NetAppAccountInner body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + return service.beginCreateOrUpdate(this.client.subscriptionId(), resourceGroupName, accountName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateOrUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateOrUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Delete a NetApp account. + * Delete the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String resourceGroupName, String accountName) { + deleteWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().last().body(); + } + + /** + * Delete a NetApp account. + * Delete the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String resourceGroupName, String accountName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, accountName), serviceCallback); + } + + /** + * Delete a NetApp account. + * Delete the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String resourceGroupName, String accountName) { + return deleteWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a NetApp account. + * Delete the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String resourceGroupName, String accountName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.subscriptionId(), resourceGroupName, accountName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Delete a NetApp account. + * Delete the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String resourceGroupName, String accountName) { + beginDeleteWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body(); + } + + /** + * Delete a NetApp account. + * Delete the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String resourceGroupName, String accountName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, accountName), serviceCallback); + } + + /** + * Delete a NetApp account. + * Delete the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String resourceGroupName, String accountName) { + return beginDeleteWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a NetApp account. + * Delete the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String resourceGroupName, String accountName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.subscriptionId(), resourceGroupName, accountName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Update a NetApp account. + * Patch the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the NetAppAccountInner object if successful. + */ + public NetAppAccountInner update(String resourceGroupName, String accountName, NetAppAccountPatch body) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, body).toBlocking().single().body(); + } + + /** + * Update a NetApp account. + * Patch the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String accountName, NetAppAccountPatch body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, accountName, body), serviceCallback); + } + + /** + * Update a NetApp account. + * Patch the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetAppAccountInner object + */ + public Observable updateAsync(String resourceGroupName, String accountName, NetAppAccountPatch body) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, body).map(new Func1, NetAppAccountInner>() { + @Override + public NetAppAccountInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update a NetApp account. + * Patch the specified NetApp account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param body NetApp Account object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the NetAppAccountInner object + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String accountName, NetAppAccountPatch body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + return service.update(this.client.subscriptionId(), resourceGroupName, accountName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse updateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/AzureNetAppFilesManagementClientImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/AzureNetAppFilesManagementClientImpl.java new file mode 100644 index 0000000000000..65a003fe71e6d --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/AzureNetAppFilesManagementClientImpl.java @@ -0,0 +1,280 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.AzureClient; +import com.microsoft.azure.AzureServiceClient; +import com.microsoft.rest.credentials.ServiceClientCredentials; +import com.microsoft.rest.RestClient; + +/** + * Initializes a new instance of the AzureNetAppFilesManagementClientImpl class. + */ +public class AzureNetAppFilesManagementClientImpl extends AzureServiceClient { + /** the {@link AzureClient} used for long running operations. */ + private AzureClient azureClient; + + /** + * Gets the {@link AzureClient} used for long running operations. + * @return the azure client; + */ + public AzureClient getAzureClient() { + return this.azureClient; + } + + /** Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. */ + private String subscriptionId; + + /** + * Gets Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + * + * @return the subscriptionId value. + */ + public String subscriptionId() { + return this.subscriptionId; + } + + /** + * Sets Subscription credentials which uniquely identify Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. + * + * @param subscriptionId the subscriptionId value. + * @return the service client itself + */ + public AzureNetAppFilesManagementClientImpl withSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /** Version of the API to be used with the client request. */ + private String apiVersion; + + /** + * Gets Version of the API to be used with the client request. + * + * @return the apiVersion value. + */ + public String apiVersion() { + return this.apiVersion; + } + + /** The preferred language for the response. */ + private String acceptLanguage; + + /** + * Gets The preferred language for the response. + * + * @return the acceptLanguage value. + */ + public String acceptLanguage() { + return this.acceptLanguage; + } + + /** + * Sets The preferred language for the response. + * + * @param acceptLanguage the acceptLanguage value. + * @return the service client itself + */ + public AzureNetAppFilesManagementClientImpl withAcceptLanguage(String acceptLanguage) { + this.acceptLanguage = acceptLanguage; + return this; + } + + /** The retry timeout in seconds for Long Running Operations. Default value is 30. */ + private int longRunningOperationRetryTimeout; + + /** + * Gets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @return the longRunningOperationRetryTimeout value. + */ + public int longRunningOperationRetryTimeout() { + return this.longRunningOperationRetryTimeout; + } + + /** + * Sets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. + * @return the service client itself + */ + public AzureNetAppFilesManagementClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { + this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; + return this; + } + + /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ + private boolean generateClientRequestId; + + /** + * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @return the generateClientRequestId value. + */ + public boolean generateClientRequestId() { + return this.generateClientRequestId; + } + + /** + * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @param generateClientRequestId the generateClientRequestId value. + * @return the service client itself + */ + public AzureNetAppFilesManagementClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { + this.generateClientRequestId = generateClientRequestId; + return this; + } + + /** + * The OperationsInner object to access its operations. + */ + private OperationsInner operations; + + /** + * Gets the OperationsInner object to access its operations. + * @return the OperationsInner object. + */ + public OperationsInner operations() { + return this.operations; + } + + /** + * The NetAppResourcesInner object to access its operations. + */ + private NetAppResourcesInner netAppResources; + + /** + * Gets the NetAppResourcesInner object to access its operations. + * @return the NetAppResourcesInner object. + */ + public NetAppResourcesInner netAppResources() { + return this.netAppResources; + } + + /** + * The AccountsInner object to access its operations. + */ + private AccountsInner accounts; + + /** + * Gets the AccountsInner object to access its operations. + * @return the AccountsInner object. + */ + public AccountsInner accounts() { + return this.accounts; + } + + /** + * The PoolsInner object to access its operations. + */ + private PoolsInner pools; + + /** + * Gets the PoolsInner object to access its operations. + * @return the PoolsInner object. + */ + public PoolsInner pools() { + return this.pools; + } + + /** + * The VolumesInner object to access its operations. + */ + private VolumesInner volumes; + + /** + * Gets the VolumesInner object to access its operations. + * @return the VolumesInner object. + */ + public VolumesInner volumes() { + return this.volumes; + } + + /** + * The MountTargetsInner object to access its operations. + */ + private MountTargetsInner mountTargets; + + /** + * Gets the MountTargetsInner object to access its operations. + * @return the MountTargetsInner object. + */ + public MountTargetsInner mountTargets() { + return this.mountTargets; + } + + /** + * The SnapshotsInner object to access its operations. + */ + private SnapshotsInner snapshots; + + /** + * Gets the SnapshotsInner object to access its operations. + * @return the SnapshotsInner object. + */ + public SnapshotsInner snapshots() { + return this.snapshots; + } + + /** + * Initializes an instance of AzureNetAppFilesManagementClient client. + * + * @param credentials the management credentials for Azure + */ + public AzureNetAppFilesManagementClientImpl(ServiceClientCredentials credentials) { + this("https://management.azure.com", credentials); + } + + /** + * Initializes an instance of AzureNetAppFilesManagementClient client. + * + * @param baseUrl the base URL of the host + * @param credentials the management credentials for Azure + */ + public AzureNetAppFilesManagementClientImpl(String baseUrl, ServiceClientCredentials credentials) { + super(baseUrl, credentials); + initialize(); + } + + /** + * Initializes an instance of AzureNetAppFilesManagementClient client. + * + * @param restClient the REST client to connect to Azure. + */ + public AzureNetAppFilesManagementClientImpl(RestClient restClient) { + super(restClient); + initialize(); + } + + protected void initialize() { + this.apiVersion = "2019-10-01"; + this.acceptLanguage = "en-US"; + this.longRunningOperationRetryTimeout = 30; + this.generateClientRequestId = true; + this.operations = new OperationsInner(restClient().retrofit(), this); + this.netAppResources = new NetAppResourcesInner(restClient().retrofit(), this); + this.accounts = new AccountsInner(restClient().retrofit(), this); + this.pools = new PoolsInner(restClient().retrofit(), this); + this.volumes = new VolumesInner(restClient().retrofit(), this); + this.mountTargets = new MountTargetsInner(restClient().retrofit(), this); + this.snapshots = new SnapshotsInner(restClient().retrofit(), this); + this.azureClient = new AzureClient(this); + } + + /** + * Gets the User-Agent header for the client. + * + * @return the user agent string. + */ + @Override + public String userAgent() { + return String.format("%s (%s, %s, auto-generated)", super.userAgent(), "AzureNetAppFilesManagementClient", "2019-10-01"); + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/CapacityPoolImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/CapacityPoolImpl.java new file mode 100644 index 0000000000000..0e4e53654e916 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/CapacityPoolImpl.java @@ -0,0 +1,186 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.CapacityPool; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.CapacityPoolPatch; +import com.microsoft.azure.management.netapp.v2019_10_01.ServiceLevel; +import java.util.Map; +import rx.functions.Func1; + +class CapacityPoolImpl extends CreatableUpdatableImpl implements CapacityPool, CapacityPool.Definition, CapacityPool.Update { + private final NetAppManager manager; + private String resourceGroupName; + private String accountName; + private String poolName; + private CapacityPoolPatch updateParameter; + + CapacityPoolImpl(String name, NetAppManager manager) { + super(name, new CapacityPoolInner()); + this.manager = manager; + // Set resource name + this.poolName = name; + // + this.updateParameter = new CapacityPoolPatch(); + } + + CapacityPoolImpl(CapacityPoolInner inner, NetAppManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.poolName = inner.name(); + // set resource ancestor and positional variables + this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups"); + this.accountName = IdParsingUtils.getValueFromIdByName(inner.id(), "netAppAccounts"); + this.poolName = IdParsingUtils.getValueFromIdByName(inner.id(), "capacityPools"); + // + this.updateParameter = new CapacityPoolPatch(); + } + + @Override + public NetAppManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + PoolsInner client = this.manager().inner().pools(); + return client.createOrUpdateAsync(this.resourceGroupName, this.accountName, this.poolName, this.inner()) + .map(new Func1() { + @Override + public CapacityPoolInner call(CapacityPoolInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + PoolsInner client = this.manager().inner().pools(); + return client.updateAsync(this.resourceGroupName, this.accountName, this.poolName, this.updateParameter) + .map(new Func1() { + @Override + public CapacityPoolInner call(CapacityPoolInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + PoolsInner client = this.manager().inner().pools(); + return client.getAsync(this.resourceGroupName, this.accountName, this.poolName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.updateParameter = new CapacityPoolPatch(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public String poolId() { + return this.inner().poolId(); + } + + @Override + public String provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public ServiceLevel serviceLevel() { + return this.inner().serviceLevel(); + } + + @Override + public long size() { + return this.inner().size(); + } + + @Override + public Map tags() { + return this.inner().getTags(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public CapacityPoolImpl withExistingNetAppAccount(String resourceGroupName, String accountName) { + this.resourceGroupName = resourceGroupName; + this.accountName = accountName; + return this; + } + + @Override + public CapacityPoolImpl withLocation(String location) { + this.inner().withLocation(location); + return this; + } + + @Override + public CapacityPoolImpl withSize(long size) { + this.inner().withSize(size); + return this; + } + + @Override + public CapacityPoolImpl withSize(Long size) { + this.updateParameter.withSize(size); + return this; + } + + @Override + public CapacityPoolImpl withServiceLevel(ServiceLevel serviceLevel) { + if (isInCreateMode()) { + this.inner().withServiceLevel(serviceLevel); + } else { + this.updateParameter.withServiceLevel(serviceLevel); + } + return this; + } + + @Override + public CapacityPoolImpl withTags(Map tags) { + if (isInCreateMode()) { + this.inner().withTags(tags); + } else { + this.updateParameter.withTags(tags); + } + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/CapacityPoolInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/CapacityPoolInner.java new file mode 100644 index 0000000000000..743ac1884044c --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/CapacityPoolInner.java @@ -0,0 +1,108 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.ServiceLevel; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.Resource; + +/** + * Capacity pool resource. + */ +@JsonFlatten +public class CapacityPoolInner extends Resource { + /** + * poolId. + * UUID v4 used to identify the Pool. + */ + @JsonProperty(value = "properties.poolId", access = JsonProperty.Access.WRITE_ONLY) + private String poolId; + + /** + * size. + * Provisioned size of the pool (in bytes). Allowed values are in 4TiB + * chunks (value must be multiply of 4398046511104). + */ + @JsonProperty(value = "properties.size", required = true) + private long size; + + /** + * serviceLevel. + * The service level of the file system. Possible values include: + * 'Standard', 'Premium', 'Ultra'. + */ + @JsonProperty(value = "properties.serviceLevel", required = true) + private ServiceLevel serviceLevel; + + /** + * Azure lifecycle management. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * Get uUID v4 used to identify the Pool. + * + * @return the poolId value + */ + public String poolId() { + return this.poolId; + } + + /** + * Get provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104). + * + * @return the size value + */ + public long size() { + return this.size; + } + + /** + * Set provisioned size of the pool (in bytes). Allowed values are in 4TiB chunks (value must be multiply of 4398046511104). + * + * @param size the size value to set + * @return the CapacityPoolInner object itself. + */ + public CapacityPoolInner withSize(long size) { + this.size = size; + return this; + } + + /** + * Get the service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra'. + * + * @return the serviceLevel value + */ + public ServiceLevel serviceLevel() { + return this.serviceLevel; + } + + /** + * Set the service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra'. + * + * @param serviceLevel the serviceLevel value to set + * @return the CapacityPoolInner object itself. + */ + public CapacityPoolInner withServiceLevel(ServiceLevel serviceLevel) { + this.serviceLevel = serviceLevel; + return this; + } + + /** + * Get azure lifecycle management. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/IdParsingUtils.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/IdParsingUtils.java new file mode 100644 index 0000000000000..3d0693510bf16 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/IdParsingUtils.java @@ -0,0 +1,57 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; +import java.util.Arrays; +import java.util.Iterator; + +class IdParsingUtils { + public static String getValueFromIdByName(String id, String name) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (part.equalsIgnoreCase(name)) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + } + return null; + } + + public static String getValueFromIdByPosition(String id, int pos) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + int index = 0; + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (index == pos) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + index++; + } + return null; + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetImpl.java new file mode 100644 index 0000000000000..a6f6c18438981 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetImpl.java @@ -0,0 +1,106 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.MountTarget; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import rx.Observable; +import java.util.Map; + +class MountTargetImpl extends WrapperImpl implements MountTarget { + private final NetAppManager manager; + + MountTargetImpl(MountTargetInner inner, NetAppManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public NetAppManager manager() { + return this.manager; + } + + + + @Override + public String endIp() { + return this.inner().endIp(); + } + + @Override + public String fileSystemId() { + return this.inner().fileSystemId(); + } + + @Override + public String gateway() { + return this.inner().gateway(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String ipAddress() { + return this.inner().ipAddress(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String mountTargetId() { + return this.inner().mountTargetId(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public String netmask() { + return this.inner().netmask(); + } + + @Override + public String provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public String smbServerFqdn() { + return this.inner().smbServerFqdn(); + } + + @Override + public String startIp() { + return this.inner().startIp(); + } + + @Override + public String subnet() { + return this.inner().subnet(); + } + + @Override + public Map tags() { + return this.inner().tags(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetInner.java new file mode 100644 index 0000000000000..0173b775a4833 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetInner.java @@ -0,0 +1,355 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; + +/** + * Mount Target. + */ +@JsonFlatten +public class MountTargetInner { + /** + * Resource location. + */ + @JsonProperty(value = "location", required = true) + private String location; + + /** + * Resource Id. + */ + @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) + private String id; + + /** + * Resource name. + */ + @JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY) + private String name; + + /** + * Resource type. + */ + @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY) + private String type; + + /** + * Resource tags. + */ + @JsonProperty(value = "tags") + private Map tags; + + /** + * mountTargetId. + * UUID v4 used to identify the MountTarget. + */ + @JsonProperty(value = "properties.mountTargetId", access = JsonProperty.Access.WRITE_ONLY) + private String mountTargetId; + + /** + * fileSystemId. + * UUID v4 used to identify the MountTarget. + */ + @JsonProperty(value = "properties.fileSystemId", required = true) + private String fileSystemId; + + /** + * ipAddress. + * The mount target's IPv4 address. + */ + @JsonProperty(value = "properties.ipAddress", access = JsonProperty.Access.WRITE_ONLY) + private String ipAddress; + + /** + * subnet. + * The subnet. + */ + @JsonProperty(value = "properties.subnet") + private String subnet; + + /** + * startIp. + * The start of IPv4 address range to use when creating a new mount target. + */ + @JsonProperty(value = "properties.startIp") + private String startIp; + + /** + * endIp. + * The end of IPv4 address range to use when creating a new mount target. + */ + @JsonProperty(value = "properties.endIp") + private String endIp; + + /** + * gateway. + * The gateway of the IPv4 address range to use when creating a new mount + * target. + */ + @JsonProperty(value = "properties.gateway") + private String gateway; + + /** + * netmask. + * The netmask of the IPv4 address range to use when creating a new mount + * target. + */ + @JsonProperty(value = "properties.netmask") + private String netmask; + + /** + * smbServerFQDN. + * The SMB server's Fully Qualified Domain Name, FQDN. + */ + @JsonProperty(value = "properties.smbServerFqdn") + private String smbServerFqdn; + + /** + * Azure lifecycle management. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * Get resource location. + * + * @return the location value + */ + public String location() { + return this.location; + } + + /** + * Set resource location. + * + * @param location the location value to set + * @return the MountTargetInner object itself. + */ + public MountTargetInner withLocation(String location) { + this.location = location; + return this; + } + + /** + * Get resource Id. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Get resource name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Get resource type. + * + * @return the type value + */ + public String type() { + return this.type; + } + + /** + * Get resource tags. + * + * @return the tags value + */ + public Map tags() { + return this.tags; + } + + /** + * Set resource tags. + * + * @param tags the tags value to set + * @return the MountTargetInner object itself. + */ + public MountTargetInner withTags(Map tags) { + this.tags = tags; + return this; + } + + /** + * Get uUID v4 used to identify the MountTarget. + * + * @return the mountTargetId value + */ + public String mountTargetId() { + return this.mountTargetId; + } + + /** + * Get uUID v4 used to identify the MountTarget. + * + * @return the fileSystemId value + */ + public String fileSystemId() { + return this.fileSystemId; + } + + /** + * Set uUID v4 used to identify the MountTarget. + * + * @param fileSystemId the fileSystemId value to set + * @return the MountTargetInner object itself. + */ + public MountTargetInner withFileSystemId(String fileSystemId) { + this.fileSystemId = fileSystemId; + return this; + } + + /** + * Get the mount target's IPv4 address. + * + * @return the ipAddress value + */ + public String ipAddress() { + return this.ipAddress; + } + + /** + * Get the subnet. + * + * @return the subnet value + */ + public String subnet() { + return this.subnet; + } + + /** + * Set the subnet. + * + * @param subnet the subnet value to set + * @return the MountTargetInner object itself. + */ + public MountTargetInner withSubnet(String subnet) { + this.subnet = subnet; + return this; + } + + /** + * Get the start of IPv4 address range to use when creating a new mount target. + * + * @return the startIp value + */ + public String startIp() { + return this.startIp; + } + + /** + * Set the start of IPv4 address range to use when creating a new mount target. + * + * @param startIp the startIp value to set + * @return the MountTargetInner object itself. + */ + public MountTargetInner withStartIp(String startIp) { + this.startIp = startIp; + return this; + } + + /** + * Get the end of IPv4 address range to use when creating a new mount target. + * + * @return the endIp value + */ + public String endIp() { + return this.endIp; + } + + /** + * Set the end of IPv4 address range to use when creating a new mount target. + * + * @param endIp the endIp value to set + * @return the MountTargetInner object itself. + */ + public MountTargetInner withEndIp(String endIp) { + this.endIp = endIp; + return this; + } + + /** + * Get the gateway of the IPv4 address range to use when creating a new mount target. + * + * @return the gateway value + */ + public String gateway() { + return this.gateway; + } + + /** + * Set the gateway of the IPv4 address range to use when creating a new mount target. + * + * @param gateway the gateway value to set + * @return the MountTargetInner object itself. + */ + public MountTargetInner withGateway(String gateway) { + this.gateway = gateway; + return this; + } + + /** + * Get the netmask of the IPv4 address range to use when creating a new mount target. + * + * @return the netmask value + */ + public String netmask() { + return this.netmask; + } + + /** + * Set the netmask of the IPv4 address range to use when creating a new mount target. + * + * @param netmask the netmask value to set + * @return the MountTargetInner object itself. + */ + public MountTargetInner withNetmask(String netmask) { + this.netmask = netmask; + return this; + } + + /** + * Get the SMB server's Fully Qualified Domain Name, FQDN. + * + * @return the smbServerFqdn value + */ + public String smbServerFqdn() { + return this.smbServerFqdn; + } + + /** + * Set the SMB server's Fully Qualified Domain Name, FQDN. + * + * @param smbServerFqdn the smbServerFqdn value to set + * @return the MountTargetInner object itself. + */ + public MountTargetInner withSmbServerFqdn(String smbServerFqdn) { + this.smbServerFqdn = smbServerFqdn; + return this; + } + + /** + * Get azure lifecycle management. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetsImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetsImpl.java new file mode 100644 index 0000000000000..ad5d93fd4dcb5 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetsImpl.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.MountTargets; +import rx.Observable; +import rx.functions.Func1; +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.MountTarget; + +class MountTargetsImpl extends WrapperImpl implements MountTargets { + private final NetAppManager manager; + + MountTargetsImpl(NetAppManager manager) { + super(manager.inner().mountTargets()); + this.manager = manager; + } + + public NetAppManager manager() { + return this.manager; + } + + private MountTargetImpl wrapModel(MountTargetInner inner) { + return new MountTargetImpl(inner, manager()); + } + + @Override + public Observable listAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + MountTargetsInner client = this.inner(); + return client.listAsync(resourceGroupName, accountName, poolName, volumeName) + .flatMap(new Func1, Observable>() { + @Override + public Observable call(List innerList) { + return Observable.from(innerList); + } + }) + .map(new Func1() { + @Override + public MountTarget call(MountTargetInner inner) { + return wrapModel(inner); + } + }); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetsInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetsInner.java new file mode 100644 index 0000000000000..295ce1ca537d7 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/MountTargetsInner.java @@ -0,0 +1,170 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.CloudException; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in MountTargets. + */ +public class MountTargetsInner { + /** The Retrofit service to perform REST calls. */ + private MountTargetsService service; + /** The service client containing this operation class. */ + private AzureNetAppFilesManagementClientImpl client; + + /** + * Initializes an instance of MountTargetsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public MountTargetsInner(Retrofit retrofit, AzureNetAppFilesManagementClientImpl client) { + this.service = retrofit.create(MountTargetsService.class); + this.client = client; + } + + /** + * The interface defining all the services for MountTargets to be + * used by Retrofit to perform actually REST calls. + */ + interface MountTargetsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.MountTargets list" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/mountTargets") + Observable> list(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Describe all mount targets. + * List all mount targets associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException 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<MountTargetInner> object if successful. + */ + public List list(String resourceGroupName, String accountName, String poolName, String volumeName) { + return listWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().single().body(); + } + + /** + * Describe all mount targets. + * List all mount targets associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback> serviceCallback) { + return ServiceFuture.fromResponse(listWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Describe all mount targets. + * List all mount targets associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable to the List<MountTargetInner> object + */ + public Observable> listAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return listWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Describe all mount targets. + * List all mount targets associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable to the List<MountTargetInner> object + */ + public Observable>> listWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + List items = null; + if (result.body() != null) { + items = result.body().items(); + } + ServiceResponse> clientResponse = new ServiceResponse>(items, result.response()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppAccountImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppAccountImpl.java new file mode 100644 index 0000000000000..56f5e4fff1183 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppAccountImpl.java @@ -0,0 +1,89 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.arm.resources.models.implementation.GroupableResourceCoreImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.NetAppAccount; +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.NetAppAccountPatch; +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.ActiveDirectory; +import rx.functions.Func1; + +class NetAppAccountImpl extends GroupableResourceCoreImpl implements NetAppAccount, NetAppAccount.Definition, NetAppAccount.Update { + private NetAppAccountPatch updateParameter; + NetAppAccountImpl(String name, NetAppAccountInner inner, NetAppManager manager) { + super(name, inner, manager); + this.updateParameter = new NetAppAccountPatch(); + } + + @Override + public Observable createResourceAsync() { + AccountsInner client = this.manager().inner().accounts(); + return client.createOrUpdateAsync(this.resourceGroupName(), this.name(), this.inner()) + .map(new Func1() { + @Override + public NetAppAccountInner call(NetAppAccountInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + AccountsInner client = this.manager().inner().accounts(); + return client.updateAsync(this.resourceGroupName(), this.name(), this.updateParameter) + .map(new Func1() { + @Override + public NetAppAccountInner call(NetAppAccountInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + AccountsInner client = this.manager().inner().accounts(); + return client.getByResourceGroupAsync(this.resourceGroupName(), this.name()); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.updateParameter = new NetAppAccountPatch(); + } + + @Override + public List activeDirectories() { + return this.inner().activeDirectories(); + } + + @Override + public String provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public NetAppAccountImpl withActiveDirectories(List activeDirectories) { + if (isInCreateMode()) { + this.inner().withActiveDirectories(activeDirectories); + } else { + this.updateParameter.withActiveDirectories(activeDirectories); + } + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppAccountInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppAccountInner.java new file mode 100644 index 0000000000000..03c11a1145dbf --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppAccountInner.java @@ -0,0 +1,63 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.ActiveDirectory; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.Resource; + +/** + * NetApp account resource. + */ +@JsonFlatten +public class NetAppAccountInner extends Resource { + /** + * Azure lifecycle management. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * Active Directories. + */ + @JsonProperty(value = "properties.activeDirectories") + private List activeDirectories; + + /** + * Get azure lifecycle management. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + + /** + * Get active Directories. + * + * @return the activeDirectories value + */ + public List activeDirectories() { + return this.activeDirectories; + } + + /** + * Set active Directories. + * + * @param activeDirectories the activeDirectories value to set + * @return the NetAppAccountInner object itself. + */ + public NetAppAccountInner withActiveDirectories(List activeDirectories) { + this.activeDirectories = activeDirectories; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppManager.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppManager.java new file mode 100644 index 0000000000000..31a2401210912 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppManager.java @@ -0,0 +1,171 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.azure.AzureResponseBuilder; +import com.microsoft.azure.credentials.AzureTokenCredentials; +import com.microsoft.azure.management.apigeneration.Beta; +import com.microsoft.azure.management.apigeneration.Beta.SinceVersion; +import com.microsoft.azure.arm.resources.AzureConfigurable; +import com.microsoft.azure.serializer.AzureJacksonAdapter; +import com.microsoft.rest.RestClient; +import com.microsoft.azure.management.netapp.v2019_10_01.Operations; +import com.microsoft.azure.management.netapp.v2019_10_01.NetAppResources; +import com.microsoft.azure.management.netapp.v2019_10_01.Accounts; +import com.microsoft.azure.management.netapp.v2019_10_01.Pools; +import com.microsoft.azure.management.netapp.v2019_10_01.Volumes; +import com.microsoft.azure.management.netapp.v2019_10_01.MountTargets; +import com.microsoft.azure.management.netapp.v2019_10_01.Snapshots; +import com.microsoft.azure.arm.resources.implementation.AzureConfigurableCoreImpl; +import com.microsoft.azure.arm.resources.implementation.ManagerCore; + +/** + * Entry point to Azure NetApp resource management. + */ +public final class NetAppManager extends ManagerCore { + private Operations operations; + private NetAppResources netAppResources; + private Accounts accounts; + private Pools pools; + private Volumes volumes; + private MountTargets mountTargets; + private Snapshots snapshots; + /** + * Get a Configurable instance that can be used to create NetAppManager with optional configuration. + * + * @return the instance allowing configurations + */ + public static Configurable configure() { + return new NetAppManager.ConfigurableImpl(); + } + /** + * Creates an instance of NetAppManager that exposes NetApp resource management API entry points. + * + * @param credentials the credentials to use + * @param subscriptionId the subscription UUID + * @return the NetAppManager + */ + public static NetAppManager authenticate(AzureTokenCredentials credentials, String subscriptionId) { + return new NetAppManager(new RestClient.Builder() + .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER) + .withCredentials(credentials) + .withSerializerAdapter(new AzureJacksonAdapter()) + .withResponseBuilderFactory(new AzureResponseBuilder.Factory()) + .build(), subscriptionId); + } + /** + * Creates an instance of NetAppManager that exposes NetApp resource management API entry points. + * + * @param restClient the RestClient to be used for API calls. + * @param subscriptionId the subscription UUID + * @return the NetAppManager + */ + public static NetAppManager authenticate(RestClient restClient, String subscriptionId) { + return new NetAppManager(restClient, subscriptionId); + } + /** + * The interface allowing configurations to be set. + */ + public interface Configurable extends AzureConfigurable { + /** + * Creates an instance of NetAppManager that exposes NetApp management API entry points. + * + * @param credentials the credentials to use + * @param subscriptionId the subscription UUID + * @return the interface exposing NetApp management API entry points that work across subscriptions + */ + NetAppManager authenticate(AzureTokenCredentials credentials, String subscriptionId); + } + + /** + * @return Entry point to manage Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(this); + } + return this.operations; + } + + /** + * @return Entry point to manage NetAppResources. + */ + public NetAppResources netAppResources() { + if (this.netAppResources == null) { + this.netAppResources = new NetAppResourcesImpl(this); + } + return this.netAppResources; + } + + /** + * @return Entry point to manage Accounts. + */ + public Accounts accounts() { + if (this.accounts == null) { + this.accounts = new AccountsImpl(this); + } + return this.accounts; + } + + /** + * @return Entry point to manage Pools. + */ + public Pools pools() { + if (this.pools == null) { + this.pools = new PoolsImpl(this); + } + return this.pools; + } + + /** + * @return Entry point to manage Volumes. + */ + public Volumes volumes() { + if (this.volumes == null) { + this.volumes = new VolumesImpl(this); + } + return this.volumes; + } + + /** + * @return Entry point to manage MountTargets. + */ + public MountTargets mountTargets() { + if (this.mountTargets == null) { + this.mountTargets = new MountTargetsImpl(this); + } + return this.mountTargets; + } + + /** + * @return Entry point to manage Snapshots. + */ + public Snapshots snapshots() { + if (this.snapshots == null) { + this.snapshots = new SnapshotsImpl(this); + } + return this.snapshots; + } + + /** + * The implementation for Configurable interface. + */ + private static final class ConfigurableImpl extends AzureConfigurableCoreImpl implements Configurable { + public NetAppManager authenticate(AzureTokenCredentials credentials, String subscriptionId) { + return NetAppManager.authenticate(buildRestClient(credentials), subscriptionId); + } + } + private NetAppManager(RestClient restClient, String subscriptionId) { + super( + restClient, + subscriptionId, + new AzureNetAppFilesManagementClientImpl(restClient).withSubscriptionId(subscriptionId)); + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppResourcesImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppResourcesImpl.java new file mode 100644 index 0000000000000..1ce372fb34fb6 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppResourcesImpl.java @@ -0,0 +1,55 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.NetAppResources; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.ResourceNameAvailability; +import com.microsoft.azure.management.netapp.v2019_10_01.CheckNameResourceTypes; + +class NetAppResourcesImpl extends WrapperImpl implements NetAppResources { + private final NetAppManager manager; + + NetAppResourcesImpl(NetAppManager manager) { + super(manager.inner().netAppResources()); + this.manager = manager; + } + + public NetAppManager manager() { + return this.manager; + } + + @Override + public Observable checkNameAvailabilityAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup) { + NetAppResourcesInner client = this.inner(); + return client.checkNameAvailabilityAsync(location, name, type, resourceGroup) + .map(new Func1() { + @Override + public ResourceNameAvailability call(ResourceNameAvailabilityInner inner) { + return new ResourceNameAvailabilityImpl(inner, manager()); + } + }); + } + + @Override + public Observable checkFilePathAvailabilityAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup) { + NetAppResourcesInner client = this.inner(); + return client.checkFilePathAvailabilityAsync(location, name, type, resourceGroup) + .map(new Func1() { + @Override + public ResourceNameAvailability call(ResourceNameAvailabilityInner inner) { + return new ResourceNameAvailabilityImpl(inner, manager()); + } + }); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppResourcesInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppResourcesInner.java new file mode 100644 index 0000000000000..5f57c4809fc5b --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/NetAppResourcesInner.java @@ -0,0 +1,283 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.management.netapp.v2019_10_01.CheckNameResourceTypes; +import com.microsoft.azure.management.netapp.v2019_10_01.ResourceNameAvailabilityRequest; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in NetAppResources. + */ +public class NetAppResourcesInner { + /** The Retrofit service to perform REST calls. */ + private NetAppResourcesService service; + /** The service client containing this operation class. */ + private AzureNetAppFilesManagementClientImpl client; + + /** + * Initializes an instance of NetAppResourcesInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public NetAppResourcesInner(Retrofit retrofit, AzureNetAppFilesManagementClientImpl client) { + this.service = retrofit.create(NetAppResourcesService.class); + this.client = client; + } + + /** + * The interface defining all the services for NetAppResources to be + * used by Retrofit to perform actually REST calls. + */ + interface NetAppResourcesService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.NetAppResources checkNameAvailability" }) + @POST("subscriptions/{subscriptionId}/providers/Microsoft.NetApp/locations/{location}/checkNameAvailability") + Observable> checkNameAvailability(@Path("subscriptionId") String subscriptionId, @Path("location") String location, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ResourceNameAvailabilityRequest body, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.NetAppResources checkFilePathAvailability" }) + @POST("subscriptions/{subscriptionId}/providers/Microsoft.NetApp/locations/{location}/checkFilePathAvailability") + Observable> checkFilePathAvailability(@Path("subscriptionId") String subscriptionId, @Path("location") String location, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body ResourceNameAvailabilityRequest body, @Header("User-Agent") String userAgent); + + } + + /** + * Check resource name availability. + * Check if a resource name is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ResourceNameAvailabilityInner object if successful. + */ + public ResourceNameAvailabilityInner checkNameAvailability(String location, String name, CheckNameResourceTypes type, String resourceGroup) { + return checkNameAvailabilityWithServiceResponseAsync(location, name, type, resourceGroup).toBlocking().single().body(); + } + + /** + * Check resource name availability. + * Check if a resource name is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture checkNameAvailabilityAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(checkNameAvailabilityWithServiceResponseAsync(location, name, type, resourceGroup), serviceCallback); + } + + /** + * Check resource name availability. + * Check if a resource name is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ResourceNameAvailabilityInner object + */ + public Observable checkNameAvailabilityAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup) { + return checkNameAvailabilityWithServiceResponseAsync(location, name, type, resourceGroup).map(new Func1, ResourceNameAvailabilityInner>() { + @Override + public ResourceNameAvailabilityInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Check resource name availability. + * Check if a resource name is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ResourceNameAvailabilityInner object + */ + public Observable> checkNameAvailabilityWithServiceResponseAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (location == null) { + throw new IllegalArgumentException("Parameter location is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (name == null) { + throw new IllegalArgumentException("Parameter name is required and cannot be null."); + } + if (type == null) { + throw new IllegalArgumentException("Parameter type is required and cannot be null."); + } + if (resourceGroup == null) { + throw new IllegalArgumentException("Parameter resourceGroup is required and cannot be null."); + } + ResourceNameAvailabilityRequest body = new ResourceNameAvailabilityRequest(); + body.withName(name); + body.withType(type); + body.withResourceGroup(resourceGroup); + return service.checkNameAvailability(this.client.subscriptionId(), location, this.client.apiVersion(), this.client.acceptLanguage(), body, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = checkNameAvailabilityDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse checkNameAvailabilityDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Check file path availability. + * Check if a file path is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ResourceNameAvailabilityInner object if successful. + */ + public ResourceNameAvailabilityInner checkFilePathAvailability(String location, String name, CheckNameResourceTypes type, String resourceGroup) { + return checkFilePathAvailabilityWithServiceResponseAsync(location, name, type, resourceGroup).toBlocking().single().body(); + } + + /** + * Check file path availability. + * Check if a file path is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture checkFilePathAvailabilityAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(checkFilePathAvailabilityWithServiceResponseAsync(location, name, type, resourceGroup), serviceCallback); + } + + /** + * Check file path availability. + * Check if a file path is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ResourceNameAvailabilityInner object + */ + public Observable checkFilePathAvailabilityAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup) { + return checkFilePathAvailabilityWithServiceResponseAsync(location, name, type, resourceGroup).map(new Func1, ResourceNameAvailabilityInner>() { + @Override + public ResourceNameAvailabilityInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Check file path availability. + * Check if a file path is available. + * + * @param location The location + * @param name Resource name to verify. + * @param type Resource type used for verification. Possible values include: 'Microsoft.NetApp/netAppAccounts', 'Microsoft.NetApp/netAppAccounts/capacityPools', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes', 'Microsoft.NetApp/netAppAccounts/capacityPools/volumes/snapshots' + * @param resourceGroup Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the ResourceNameAvailabilityInner object + */ + public Observable> checkFilePathAvailabilityWithServiceResponseAsync(String location, String name, CheckNameResourceTypes type, String resourceGroup) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (location == null) { + throw new IllegalArgumentException("Parameter location is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + if (name == null) { + throw new IllegalArgumentException("Parameter name is required and cannot be null."); + } + if (type == null) { + throw new IllegalArgumentException("Parameter type is required and cannot be null."); + } + if (resourceGroup == null) { + throw new IllegalArgumentException("Parameter resourceGroup is required and cannot be null."); + } + ResourceNameAvailabilityRequest body = new ResourceNameAvailabilityRequest(); + body.withName(name); + body.withType(type); + body.withResourceGroup(resourceGroup); + return service.checkFilePathAvailability(this.client.subscriptionId(), location, this.client.apiVersion(), this.client.acceptLanguage(), body, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = checkFilePathAvailabilityDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse checkFilePathAvailabilityDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationImpl.java new file mode 100644 index 0000000000000..510609035663e --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationImpl.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.Operation; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.OperationDisplay; +import com.microsoft.azure.management.netapp.v2019_10_01.ServiceSpecification; + +class OperationImpl extends WrapperImpl implements Operation { + private final NetAppManager manager; + OperationImpl(OperationInner inner, NetAppManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public NetAppManager manager() { + return this.manager; + } + + @Override + public OperationDisplay display() { + return this.inner().display(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public String origin() { + return this.inner().origin(); + } + + @Override + public ServiceSpecification serviceSpecification() { + return this.inner().serviceSpecification(); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationInner.java new file mode 100644 index 0000000000000..25add61f5260b --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationInner.java @@ -0,0 +1,125 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.OperationDisplay; +import com.microsoft.azure.management.netapp.v2019_10_01.ServiceSpecification; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; + +/** + * Microsoft.NetApp REST API operation definition. + */ +@JsonFlatten +public class OperationInner { + /** + * Operation name: {provider}/{resource}/{operation}. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Display metadata associated with the operation. + */ + @JsonProperty(value = "display") + private OperationDisplay display; + + /** + * The origin of operations. + */ + @JsonProperty(value = "origin") + private String origin; + + /** + * One property of operation, include metric specifications. + */ + @JsonProperty(value = "properties.serviceSpecification") + private ServiceSpecification serviceSpecification; + + /** + * Get operation name: {provider}/{resource}/{operation}. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set operation name: {provider}/{resource}/{operation}. + * + * @param name the name value to set + * @return the OperationInner object itself. + */ + public OperationInner withName(String name) { + this.name = name; + return this; + } + + /** + * Get display metadata associated with the operation. + * + * @return the display value + */ + public OperationDisplay display() { + return this.display; + } + + /** + * Set display metadata associated with the 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 of operations. + * + * @return the origin value + */ + public String origin() { + return this.origin; + } + + /** + * Set the origin of operations. + * + * @param origin the origin value to set + * @return the OperationInner object itself. + */ + public OperationInner withOrigin(String origin) { + this.origin = origin; + return this; + } + + /** + * Get one property of operation, include metric specifications. + * + * @return the serviceSpecification value + */ + public ServiceSpecification serviceSpecification() { + return this.serviceSpecification; + } + + /** + * Set one property of operation, include metric specifications. + * + * @param serviceSpecification the serviceSpecification value to set + * @return the OperationInner object itself. + */ + public OperationInner withServiceSpecification(ServiceSpecification serviceSpecification) { + this.serviceSpecification = serviceSpecification; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationsImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationsImpl.java new file mode 100644 index 0000000000000..024b45ebd640b --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationsImpl.java @@ -0,0 +1,49 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.Operations; +import rx.functions.Func1; +import rx.Observable; +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.Operation; + +class OperationsImpl extends WrapperImpl implements Operations { + private final NetAppManager manager; + + OperationsImpl(NetAppManager manager) { + super(manager.inner().operations()); + this.manager = manager; + } + + public NetAppManager manager() { + return this.manager; + } + + @Override + public Observable listAsync() { + OperationsInner client = this.inner(); + return client.listAsync() + .flatMap(new Func1, Observable>() { + @Override + public Observable call(List innerList) { + return Observable.from(innerList); + } + }) + .map(new Func1() { + @Override + public Operation call(OperationInner inner) { + return new OperationImpl(inner, manager()); + } + }); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationsInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationsInner.java new file mode 100644 index 0000000000000..0f3a4974edc60 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/OperationsInner.java @@ -0,0 +1,138 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.CloudException; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Operations. + */ +public class OperationsInner { + /** The Retrofit service to perform REST calls. */ + private OperationsService service; + /** The service client containing this operation class. */ + private AzureNetAppFilesManagementClientImpl client; + + /** + * Initializes an instance of OperationsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public OperationsInner(Retrofit retrofit, AzureNetAppFilesManagementClientImpl client) { + this.service = retrofit.create(OperationsService.class); + this.client = client; + } + + /** + * The interface defining all the services for Operations to be + * used by Retrofit to perform actually REST calls. + */ + interface OperationsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Operations list" }) + @GET("providers/Microsoft.NetApp/operations") + Observable> list(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Describes the Resource Provider. + * Lists all of the available Microsoft.NetApp Rest API operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException 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<OperationInner> object if successful. + */ + public List list() { + return listWithServiceResponseAsync().toBlocking().single().body(); + } + + /** + * Describes the Resource Provider. + * Lists all of the available Microsoft.NetApp Rest API operations. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ServiceCallback> serviceCallback) { + return ServiceFuture.fromResponse(listWithServiceResponseAsync(), serviceCallback); + } + + /** + * Describes the Resource Provider. + * Lists all of the available Microsoft.NetApp Rest API operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the List<OperationInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync().map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Describes the Resource Provider. + * Lists all of the available Microsoft.NetApp Rest API operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the List<OperationInner> object + */ + public Observable>> listWithServiceResponseAsync() { + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + List items = null; + if (result.body() != null) { + items = result.body().items(); + } + ServiceResponse> clientResponse = new ServiceResponse>(items, result.response()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/PageImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/PageImpl.java new file mode 100644 index 0000000000000..509333ab8cc2e --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/PageImpl.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.Page; +import java.util.List; + +/** + * An instance of this class defines a page of Azure resources and a link to + * get the next page of resources, if any. + * + * @param type of Azure resource + */ +public class PageImpl implements Page { + /** + * The link to the next page. + */ + @JsonProperty("") + private String nextPageLink; + + /** + * The list of items. + */ + @JsonProperty("value") + private List items; + + /** + * Gets the link to the next page. + * + * @return the link to the next page. + */ + @Override + public String nextPageLink() { + return this.nextPageLink; + } + + /** + * Gets the list of items. + * + * @return the list of items in {@link List}. + */ + @Override + public List items() { + return items; + } + + /** + * Sets the link to the next page. + * + * @param nextPageLink the link to the next page. + * @return this Page object itself. + */ + public PageImpl setNextPageLink(String nextPageLink) { + this.nextPageLink = nextPageLink; + return this; + } + + /** + * Sets the list of items. + * + * @param items the list of items in {@link List}. + * @return this Page object itself. + */ + public PageImpl setItems(List items) { + this.items = items; + return this; + } +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/PoolsImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/PoolsImpl.java new file mode 100644 index 0000000000000..96332363d50cb --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/PoolsImpl.java @@ -0,0 +1,85 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.Pools; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.CapacityPool; + +class PoolsImpl extends WrapperImpl implements Pools { + private final NetAppManager manager; + + PoolsImpl(NetAppManager manager) { + super(manager.inner().pools()); + this.manager = manager; + } + + public NetAppManager manager() { + return this.manager; + } + + @Override + public CapacityPoolImpl define(String name) { + return wrapModel(name); + } + + private CapacityPoolImpl wrapModel(CapacityPoolInner inner) { + return new CapacityPoolImpl(inner, manager()); + } + + private CapacityPoolImpl wrapModel(String name) { + return new CapacityPoolImpl(name, this.manager()); + } + + @Override + public Observable listAsync(String resourceGroupName, String accountName) { + PoolsInner client = this.inner(); + return client.listAsync(resourceGroupName, accountName) + .flatMap(new Func1, Observable>() { + @Override + public Observable call(List innerList) { + return Observable.from(innerList); + } + }) + .map(new Func1() { + @Override + public CapacityPool call(CapacityPoolInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String resourceGroupName, String accountName, String poolName) { + PoolsInner client = this.inner(); + return client.getAsync(resourceGroupName, accountName, poolName) + .flatMap(new Func1>() { + @Override + public Observable call(CapacityPoolInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((CapacityPool)wrapModel(inner)); + } + } + }); + } + + @Override + public Completable deleteAsync(String resourceGroupName, String accountName, String poolName) { + PoolsInner client = this.inner(); + return client.deleteAsync(resourceGroupName, accountName, poolName).toCompletable(); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/PoolsInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/PoolsInner.java new file mode 100644 index 0000000000000..d111d54b6a479 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/PoolsInner.java @@ -0,0 +1,760 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.management.netapp.v2019_10_01.CapacityPoolPatch; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Pools. + */ +public class PoolsInner { + /** The Retrofit service to perform REST calls. */ + private PoolsService service; + /** The service client containing this operation class. */ + private AzureNetAppFilesManagementClientImpl client; + + /** + * Initializes an instance of PoolsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public PoolsInner(Retrofit retrofit, AzureNetAppFilesManagementClientImpl client) { + this.service = retrofit.create(PoolsService.class); + this.client = client; + } + + /** + * The interface defining all the services for Pools to be + * used by Retrofit to perform actually REST calls. + */ + interface PoolsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Pools list" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools") + Observable> list(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Pools get" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}") + Observable> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Pools createOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}") + Observable> createOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Body CapacityPoolInner body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Pools beginCreateOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}") + Observable> beginCreateOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Body CapacityPoolInner body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Pools update" }) + @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}") + Observable> update(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Body CapacityPoolPatch body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Pools delete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Pools beginDelete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Describe all Capacity Pools. + * List all capacity pools in the NetApp Account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException 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<CapacityPoolInner> object if successful. + */ + public List list(String resourceGroupName, String accountName) { + return listWithServiceResponseAsync(resourceGroupName, accountName).toBlocking().single().body(); + } + + /** + * Describe all Capacity Pools. + * List all capacity pools in the NetApp Account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(String resourceGroupName, String accountName, final ServiceCallback> serviceCallback) { + return ServiceFuture.fromResponse(listWithServiceResponseAsync(resourceGroupName, accountName), serviceCallback); + } + + /** + * Describe all Capacity Pools. + * List all capacity pools in the NetApp Account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the List<CapacityPoolInner> object + */ + public Observable> listAsync(String resourceGroupName, String accountName) { + return listWithServiceResponseAsync(resourceGroupName, accountName).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Describe all Capacity Pools. + * List all capacity pools in the NetApp Account. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the List<CapacityPoolInner> object + */ + public Observable>> listWithServiceResponseAsync(String resourceGroupName, String accountName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.subscriptionId(), resourceGroupName, accountName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + List items = null; + if (result.body() != null) { + items = result.body().items(); + } + ServiceResponse> clientResponse = new ServiceResponse>(items, result.response()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Describe a Capacity Pool. + * Get details of the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the CapacityPoolInner object if successful. + */ + public CapacityPoolInner get(String resourceGroupName, String accountName, String poolName) { + return getWithServiceResponseAsync(resourceGroupName, accountName, poolName).toBlocking().single().body(); + } + + /** + * Describe a Capacity Pool. + * Get details of the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String resourceGroupName, String accountName, String poolName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, accountName, poolName), serviceCallback); + } + + /** + * Describe a Capacity Pool. + * Get details of the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the CapacityPoolInner object + */ + public Observable getAsync(String resourceGroupName, String accountName, String poolName) { + return getWithServiceResponseAsync(resourceGroupName, accountName, poolName).map(new Func1, CapacityPoolInner>() { + @Override + public CapacityPoolInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Describe a Capacity Pool. + * Get details of the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the CapacityPoolInner object + */ + public Observable> getWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.subscriptionId(), resourceGroupName, accountName, poolName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Create or Update the specified capacity pool within the resource group. + * Create or Update a capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the CapacityPoolInner object if successful. + */ + public CapacityPoolInner createOrUpdate(String resourceGroupName, String accountName, String poolName, CapacityPoolInner body) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, body).toBlocking().last().body(); + } + + /** + * Create or Update the specified capacity pool within the resource group. + * Create or Update a capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAsync(String resourceGroupName, String accountName, String poolName, CapacityPoolInner body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, body), serviceCallback); + } + + /** + * Create or Update the specified capacity pool within the resource group. + * Create or Update a capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createOrUpdateAsync(String resourceGroupName, String accountName, String poolName, CapacityPoolInner body) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, body).map(new Func1, CapacityPoolInner>() { + @Override + public CapacityPoolInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create or Update the specified capacity pool within the resource group. + * Create or Update a capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, CapacityPoolInner body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + Observable> observable = service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, accountName, poolName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Create or Update the specified capacity pool within the resource group. + * Create or Update a capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the CapacityPoolInner object if successful. + */ + public CapacityPoolInner beginCreateOrUpdate(String resourceGroupName, String accountName, String poolName, CapacityPoolInner body) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, body).toBlocking().single().body(); + } + + /** + * Create or Update the specified capacity pool within the resource group. + * Create or Update a capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateOrUpdateAsync(String resourceGroupName, String accountName, String poolName, CapacityPoolInner body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, body), serviceCallback); + } + + /** + * Create or Update the specified capacity pool within the resource group. + * Create or Update a capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the CapacityPoolInner object + */ + public Observable beginCreateOrUpdateAsync(String resourceGroupName, String accountName, String poolName, CapacityPoolInner body) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, body).map(new Func1, CapacityPoolInner>() { + @Override + public CapacityPoolInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create or Update the specified capacity pool within the resource group. + * Create or Update a capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the CapacityPoolInner object + */ + public Observable> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, CapacityPoolInner body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + return service.beginCreateOrUpdate(this.client.subscriptionId(), resourceGroupName, accountName, poolName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateOrUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateOrUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Update a capacity pool. + * Patch the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the CapacityPoolInner object if successful. + */ + public CapacityPoolInner update(String resourceGroupName, String accountName, String poolName, CapacityPoolPatch body) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, body).toBlocking().single().body(); + } + + /** + * Update a capacity pool. + * Patch the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String accountName, String poolName, CapacityPoolPatch body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, body), serviceCallback); + } + + /** + * Update a capacity pool. + * Patch the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the CapacityPoolInner object + */ + public Observable updateAsync(String resourceGroupName, String accountName, String poolName, CapacityPoolPatch body) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, body).map(new Func1, CapacityPoolInner>() { + @Override + public CapacityPoolInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update a capacity pool. + * Patch the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param body Capacity pool object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the CapacityPoolInner object + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, CapacityPoolPatch body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + return service.update(this.client.subscriptionId(), resourceGroupName, accountName, poolName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse updateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Delete a capacity pool. + * Delete the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String resourceGroupName, String accountName, String poolName) { + deleteWithServiceResponseAsync(resourceGroupName, accountName, poolName).toBlocking().last().body(); + } + + /** + * Delete a capacity pool. + * Delete the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String resourceGroupName, String accountName, String poolName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, accountName, poolName), serviceCallback); + } + + /** + * Delete a capacity pool. + * Delete the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String resourceGroupName, String accountName, String poolName) { + return deleteWithServiceResponseAsync(resourceGroupName, accountName, poolName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a capacity pool. + * Delete the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.subscriptionId(), resourceGroupName, accountName, poolName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Delete a capacity pool. + * Delete the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String resourceGroupName, String accountName, String poolName) { + beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, poolName).toBlocking().single().body(); + } + + /** + * Delete a capacity pool. + * Delete the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String resourceGroupName, String accountName, String poolName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, poolName), serviceCallback); + } + + /** + * Delete a capacity pool. + * Delete the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String resourceGroupName, String accountName, String poolName) { + return beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, poolName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a capacity pool. + * Delete the specified capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.subscriptionId(), resourceGroupName, accountName, poolName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ReplicationStatusImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ReplicationStatusImpl.java new file mode 100644 index 0000000000000..2b996deb0b8e6 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ReplicationStatusImpl.java @@ -0,0 +1,53 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.ReplicationStatus; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.MirrorState; +import com.microsoft.azure.management.netapp.v2019_10_01.RelationshipStatus; + +class ReplicationStatusImpl extends WrapperImpl implements ReplicationStatus { + private final NetAppManager manager; + ReplicationStatusImpl(ReplicationStatusInner inner, NetAppManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public NetAppManager manager() { + return this.manager; + } + + @Override + public String errorMessage() { + return this.inner().errorMessage(); + } + + @Override + public Boolean healthy() { + return this.inner().healthy(); + } + + @Override + public MirrorState mirrorState() { + return this.inner().mirrorState(); + } + + @Override + public RelationshipStatus relationshipStatus() { + return this.inner().relationshipStatus(); + } + + @Override + public String totalProgress() { + return this.inner().totalProgress(); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ReplicationStatusInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ReplicationStatusInner.java new file mode 100644 index 0000000000000..1bec2b3e1ae74 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ReplicationStatusInner.java @@ -0,0 +1,151 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.RelationshipStatus; +import com.microsoft.azure.management.netapp.v2019_10_01.MirrorState; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Replication status. + */ +public class ReplicationStatusInner { + /** + * Replication health check. + */ + @JsonProperty(value = "healthy") + private Boolean healthy; + + /** + * Status of the mirror relationship. Possible values include: 'Idle', + * 'Transferring'. + */ + @JsonProperty(value = "relationshipStatus") + private RelationshipStatus relationshipStatus; + + /** + * The status of the replication. Possible values include: 'Uninitialized', + * 'Mirrored', 'Broken'. + */ + @JsonProperty(value = "mirrorState") + private MirrorState mirrorState; + + /** + * The progress of the replication. + */ + @JsonProperty(value = "totalProgress") + private String totalProgress; + + /** + * Displays error message if the replication is in an error state. + */ + @JsonProperty(value = "errorMessage") + private String errorMessage; + + /** + * Get replication health check. + * + * @return the healthy value + */ + public Boolean healthy() { + return this.healthy; + } + + /** + * Set replication health check. + * + * @param healthy the healthy value to set + * @return the ReplicationStatusInner object itself. + */ + public ReplicationStatusInner withHealthy(Boolean healthy) { + this.healthy = healthy; + return this; + } + + /** + * Get status of the mirror relationship. Possible values include: 'Idle', 'Transferring'. + * + * @return the relationshipStatus value + */ + public RelationshipStatus relationshipStatus() { + return this.relationshipStatus; + } + + /** + * Set status of the mirror relationship. Possible values include: 'Idle', 'Transferring'. + * + * @param relationshipStatus the relationshipStatus value to set + * @return the ReplicationStatusInner object itself. + */ + public ReplicationStatusInner withRelationshipStatus(RelationshipStatus relationshipStatus) { + this.relationshipStatus = relationshipStatus; + return this; + } + + /** + * Get the status of the replication. Possible values include: 'Uninitialized', 'Mirrored', 'Broken'. + * + * @return the mirrorState value + */ + public MirrorState mirrorState() { + return this.mirrorState; + } + + /** + * Set the status of the replication. Possible values include: 'Uninitialized', 'Mirrored', 'Broken'. + * + * @param mirrorState the mirrorState value to set + * @return the ReplicationStatusInner object itself. + */ + public ReplicationStatusInner withMirrorState(MirrorState mirrorState) { + this.mirrorState = mirrorState; + return this; + } + + /** + * Get the progress of the replication. + * + * @return the totalProgress value + */ + public String totalProgress() { + return this.totalProgress; + } + + /** + * Set the progress of the replication. + * + * @param totalProgress the totalProgress value to set + * @return the ReplicationStatusInner object itself. + */ + public ReplicationStatusInner withTotalProgress(String totalProgress) { + this.totalProgress = totalProgress; + return this; + } + + /** + * Get displays error message if the replication is in an error state. + * + * @return the errorMessage value + */ + public String errorMessage() { + return this.errorMessage; + } + + /** + * Set displays error message if the replication is in an error state. + * + * @param errorMessage the errorMessage value to set + * @return the ReplicationStatusInner object itself. + */ + public ReplicationStatusInner withErrorMessage(String errorMessage) { + this.errorMessage = errorMessage; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ResourceNameAvailabilityImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ResourceNameAvailabilityImpl.java new file mode 100644 index 0000000000000..ed2aa55706165 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ResourceNameAvailabilityImpl.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.ResourceNameAvailability; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.InAvailabilityReasonType; + +class ResourceNameAvailabilityImpl extends WrapperImpl implements ResourceNameAvailability { + private final NetAppManager manager; + ResourceNameAvailabilityImpl(ResourceNameAvailabilityInner inner, NetAppManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public NetAppManager manager() { + return this.manager; + } + + @Override + public Boolean isAvailable() { + return this.inner().isAvailable(); + } + + @Override + public String message() { + return this.inner().message(); + } + + @Override + public InAvailabilityReasonType reason() { + return this.inner().reason(); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ResourceNameAvailabilityInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ResourceNameAvailabilityInner.java new file mode 100644 index 0000000000000..9dcda1c75c419 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/ResourceNameAvailabilityInner.java @@ -0,0 +1,106 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.InAvailabilityReasonType; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Information regarding availability of a resource name. + */ +public class ResourceNameAvailabilityInner { + /** + * <code>true</code> indicates name is valid and available. + * <code>false</code> indicates the name is invalid, + * unavailable, or both. + */ + @JsonProperty(value = "isAvailable") + private Boolean isAvailable; + + /** + * <code>Invalid</code> indicates the name provided does not + * match Azure App Service naming requirements. + * <code>AlreadyExists</code> indicates that the name is + * already in use and is therefore unavailable. Possible values include: + * 'Invalid', 'AlreadyExists'. + */ + @JsonProperty(value = "reason") + private InAvailabilityReasonType reason; + + /** + * If reason == invalid, provide the user with the reason why the given + * name is invalid, and provide the resource naming requirements so that + * the user can select a valid name. If reason == AlreadyExists, explain + * that resource name is already in use, and direct them to select a + * different name. + */ + @JsonProperty(value = "message") + private String message; + + /** + * Get <code>true</code> indicates name is valid and available. <code>false</code> indicates the name is invalid, unavailable, or both. + * + * @return the isAvailable value + */ + public Boolean isAvailable() { + return this.isAvailable; + } + + /** + * Set <code>true</code> indicates name is valid and available. <code>false</code> indicates the name is invalid, unavailable, or both. + * + * @param isAvailable the isAvailable value to set + * @return the ResourceNameAvailabilityInner object itself. + */ + public ResourceNameAvailabilityInner withIsAvailable(Boolean isAvailable) { + this.isAvailable = isAvailable; + return this; + } + + /** + * Get <code>Invalid</code> indicates the name provided does not match Azure App Service naming requirements. <code>AlreadyExists</code> indicates that the name is already in use and is therefore unavailable. Possible values include: 'Invalid', 'AlreadyExists'. + * + * @return the reason value + */ + public InAvailabilityReasonType reason() { + return this.reason; + } + + /** + * Set <code>Invalid</code> indicates the name provided does not match Azure App Service naming requirements. <code>AlreadyExists</code> indicates that the name is already in use and is therefore unavailable. Possible values include: 'Invalid', 'AlreadyExists'. + * + * @param reason the reason value to set + * @return the ResourceNameAvailabilityInner object itself. + */ + public ResourceNameAvailabilityInner withReason(InAvailabilityReasonType reason) { + this.reason = reason; + return this; + } + + /** + * Get if reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that resource name is already in use, and direct them to select a different name. + * + * @return the message value + */ + public String message() { + return this.message; + } + + /** + * Set if reason == invalid, provide the user with the reason why the given name is invalid, and provide the resource naming requirements so that the user can select a valid name. If reason == AlreadyExists, explain that resource name is already in use, and direct them to select a different name. + * + * @param message the message value to set + * @return the ResourceNameAvailabilityInner object itself. + */ + public ResourceNameAvailabilityInner withMessage(String message) { + this.message = message; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotImpl.java new file mode 100644 index 0000000000000..e84d9ffb7bebe --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotImpl.java @@ -0,0 +1,150 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.Snapshot; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import org.joda.time.DateTime; +import java.util.Map; + +class SnapshotImpl extends CreatableUpdatableImpl implements Snapshot, Snapshot.Definition, Snapshot.Update { + private final NetAppManager manager; + private String resourceGroupName; + private String accountName; + private String poolName; + private String volumeName; + private String snapshotName; + + SnapshotImpl(String name, NetAppManager manager) { + super(name, new SnapshotInner()); + this.manager = manager; + // Set resource name + this.snapshotName = name; + // + } + + SnapshotImpl(SnapshotInner inner, NetAppManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.snapshotName = inner.name(); + // set resource ancestor and positional variables + this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups"); + this.accountName = IdParsingUtils.getValueFromIdByName(inner.id(), "netAppAccounts"); + this.poolName = IdParsingUtils.getValueFromIdByName(inner.id(), "capacityPools"); + this.volumeName = IdParsingUtils.getValueFromIdByName(inner.id(), "volumes"); + this.snapshotName = IdParsingUtils.getValueFromIdByName(inner.id(), "snapshots"); + // + } + + @Override + public NetAppManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + SnapshotsInner client = this.manager().inner().snapshots(); + return client.createAsync(this.resourceGroupName, this.accountName, this.poolName, this.volumeName, this.snapshotName, this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + SnapshotsInner client = this.manager().inner().snapshots(); + return client.createAsync(this.resourceGroupName, this.accountName, this.poolName, this.volumeName, this.snapshotName, this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + SnapshotsInner client = this.manager().inner().snapshots(); + return client.getAsync(this.resourceGroupName, this.accountName, this.poolName, this.volumeName, this.snapshotName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + + @Override + public DateTime created() { + return this.inner().created(); + } + + @Override + public String fileSystemId() { + return this.inner().fileSystemId(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public String provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public String snapshotId() { + return this.inner().snapshotId(); + } + + @Override + public Map tags() { + return this.inner().getTags(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public SnapshotImpl withExistingVolume(String resourceGroupName, String accountName, String poolName, String volumeName) { + this.resourceGroupName = resourceGroupName; + this.accountName = accountName; + this.poolName = poolName; + this.volumeName = volumeName; + return this; + } + + @Override + public SnapshotImpl withLocation(String location) { + this.inner().withLocation(location); + return this; + } + + @Override + public SnapshotImpl withFileSystemId(String fileSystemId) { + this.inner().withFileSystemId(fileSystemId); + return this; + } + + @Override + public SnapshotImpl withTags(Map tags) { + this.inner().withTags(tags); + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotInner.java new file mode 100644 index 0000000000000..1153bfe25c634 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotInner.java @@ -0,0 +1,95 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.Resource; + +/** + * Snapshot of a Volume. + */ +@JsonFlatten +public class SnapshotInner extends Resource { + /** + * snapshotId. + * UUID v4 used to identify the Snapshot. + */ + @JsonProperty(value = "properties.snapshotId", access = JsonProperty.Access.WRITE_ONLY) + private String snapshotId; + + /** + * fileSystemId. + * UUID v4 used to identify the FileSystem. + */ + @JsonProperty(value = "properties.fileSystemId") + private String fileSystemId; + + /** + * name. + * The creation date of the snapshot. + */ + @JsonProperty(value = "properties.created", access = JsonProperty.Access.WRITE_ONLY) + private DateTime created; + + /** + * Azure lifecycle management. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * Get uUID v4 used to identify the Snapshot. + * + * @return the snapshotId value + */ + public String snapshotId() { + return this.snapshotId; + } + + /** + * Get uUID v4 used to identify the FileSystem. + * + * @return the fileSystemId value + */ + public String fileSystemId() { + return this.fileSystemId; + } + + /** + * Set uUID v4 used to identify the FileSystem. + * + * @param fileSystemId the fileSystemId value to set + * @return the SnapshotInner object itself. + */ + public SnapshotInner withFileSystemId(String fileSystemId) { + this.fileSystemId = fileSystemId; + return this; + } + + /** + * Get the creation date of the snapshot. + * + * @return the created value + */ + public DateTime created() { + return this.created; + } + + /** + * Get azure lifecycle management. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotsImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotsImpl.java new file mode 100644 index 0000000000000..9acf40a0d860c --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotsImpl.java @@ -0,0 +1,85 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.Snapshots; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.Snapshot; + +class SnapshotsImpl extends WrapperImpl implements Snapshots { + private final NetAppManager manager; + + SnapshotsImpl(NetAppManager manager) { + super(manager.inner().snapshots()); + this.manager = manager; + } + + public NetAppManager manager() { + return this.manager; + } + + @Override + public SnapshotImpl define(String name) { + return wrapModel(name); + } + + private SnapshotImpl wrapModel(SnapshotInner inner) { + return new SnapshotImpl(inner, manager()); + } + + private SnapshotImpl wrapModel(String name) { + return new SnapshotImpl(name, this.manager()); + } + + @Override + public Observable listAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + SnapshotsInner client = this.inner(); + return client.listAsync(resourceGroupName, accountName, poolName, volumeName) + .flatMap(new Func1, Observable>() { + @Override + public Observable call(List innerList) { + return Observable.from(innerList); + } + }) + .map(new Func1() { + @Override + public Snapshot call(SnapshotInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + SnapshotsInner client = this.inner(); + return client.getAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName) + .flatMap(new Func1>() { + @Override + public Observable call(SnapshotInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((Snapshot)wrapModel(inner)); + } + } + }); + } + + @Override + public Completable deleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + SnapshotsInner client = this.inner(); + return client.deleteAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).toCompletable(); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotsInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotsInner.java new file mode 100644 index 0000000000000..b51169eef0c7e --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/SnapshotsInner.java @@ -0,0 +1,965 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.management.netapp.v2019_10_01.SnapshotPatch; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Snapshots. + */ +public class SnapshotsInner { + /** The Retrofit service to perform REST calls. */ + private SnapshotsService service; + /** The service client containing this operation class. */ + private AzureNetAppFilesManagementClientImpl client; + + /** + * Initializes an instance of SnapshotsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public SnapshotsInner(Retrofit retrofit, AzureNetAppFilesManagementClientImpl client) { + this.service = retrofit.create(SnapshotsService.class); + this.client = client; + } + + /** + * The interface defining all the services for Snapshots to be + * used by Retrofit to perform actually REST calls. + */ + interface SnapshotsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Snapshots list" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots") + Observable> list(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Snapshots get" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}") + Observable> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Path("snapshotName") String snapshotName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Snapshots create" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}") + Observable> create(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Path("snapshotName") String snapshotName, @Body SnapshotInner body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Snapshots beginCreate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}") + Observable> beginCreate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Path("snapshotName") String snapshotName, @Body SnapshotInner body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Snapshots update" }) + @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}") + Observable> update(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Path("snapshotName") String snapshotName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body SnapshotPatch body, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Snapshots delete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Path("snapshotName") String snapshotName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Snapshots beginDelete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/snapshots/{snapshotName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Path("snapshotName") String snapshotName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Describe all snapshots. + * List all snapshots associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException 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<SnapshotInner> object if successful. + */ + public List list(String resourceGroupName, String accountName, String poolName, String volumeName) { + return listWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().single().body(); + } + + /** + * Describe all snapshots. + * List all snapshots associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback> serviceCallback) { + return ServiceFuture.fromResponse(listWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Describe all snapshots. + * List all snapshots associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable to the List<SnapshotInner> object + */ + public Observable> listAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return listWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Describe all snapshots. + * List all snapshots associated with the volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable to the List<SnapshotInner> object + */ + public Observable>> listWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + List items = null; + if (result.body() != null) { + items = result.body().items(); + } + ServiceResponse> clientResponse = new ServiceResponse>(items, result.response()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Describe a snapshot. + * Get details of the specified snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SnapshotInner object if successful. + */ + public SnapshotInner get(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + return getWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).toBlocking().single().body(); + } + + /** + * Describe a snapshot. + * Get details of the specified snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName), serviceCallback); + } + + /** + * Describe a snapshot. + * Get details of the specified snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SnapshotInner object + */ + public Observable getAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + return getWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).map(new Func1, SnapshotInner>() { + @Override + public SnapshotInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Describe a snapshot. + * Get details of the specified snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SnapshotInner object + */ + public Observable> getWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (snapshotName == null) { + throw new IllegalArgumentException("Parameter snapshotName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, snapshotName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Create a snapshot. + * Create the specified snapshot within the given volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param body Snapshot object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SnapshotInner object if successful. + */ + public SnapshotInner create(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, SnapshotInner body) { + return createWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, body).toBlocking().last().body(); + } + + /** + * Create a snapshot. + * Create the specified snapshot within the given volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param body Snapshot object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, SnapshotInner body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, body), serviceCallback); + } + + /** + * Create a snapshot. + * Create the specified snapshot within the given volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param body Snapshot object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, SnapshotInner body) { + return createWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, body).map(new Func1, SnapshotInner>() { + @Override + public SnapshotInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create a snapshot. + * Create the specified snapshot within the given volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param body Snapshot object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, SnapshotInner body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (snapshotName == null) { + throw new IllegalArgumentException("Parameter snapshotName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + Observable> observable = service.create(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, snapshotName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Create a snapshot. + * Create the specified snapshot within the given volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param body Snapshot object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SnapshotInner object if successful. + */ + public SnapshotInner beginCreate(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, SnapshotInner body) { + return beginCreateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, body).toBlocking().single().body(); + } + + /** + * Create a snapshot. + * Create the specified snapshot within the given volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param body Snapshot object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, SnapshotInner body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, body), serviceCallback); + } + + /** + * Create a snapshot. + * Create the specified snapshot within the given volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param body Snapshot object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SnapshotInner object + */ + public Observable beginCreateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, SnapshotInner body) { + return beginCreateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, body).map(new Func1, SnapshotInner>() { + @Override + public SnapshotInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create a snapshot. + * Create the specified snapshot within the given volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param body Snapshot object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SnapshotInner object + */ + public Observable> beginCreateWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, SnapshotInner body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (snapshotName == null) { + throw new IllegalArgumentException("Parameter snapshotName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + return service.beginCreate(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, snapshotName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(201, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Update a snapshot. + * Patch a snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SnapshotInner object if successful. + */ + public SnapshotInner update(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).toBlocking().single().body(); + } + + /** + * Update a snapshot. + * Patch a snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName), serviceCallback); + } + + /** + * Update a snapshot. + * Patch a snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SnapshotInner object + */ + public Observable updateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).map(new Func1, SnapshotInner>() { + @Override + public SnapshotInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update a snapshot. + * Patch a snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SnapshotInner object + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (snapshotName == null) { + throw new IllegalArgumentException("Parameter snapshotName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final Map tags = null; + SnapshotPatch body = new SnapshotPatch(); + body.withTags(null); + return service.update(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, snapshotName, this.client.apiVersion(), this.client.acceptLanguage(), body, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Update a snapshot. + * Patch a snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param tags Resource tags + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SnapshotInner object if successful. + */ + public SnapshotInner update(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, Map tags) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, tags).toBlocking().single().body(); + } + + /** + * Update a snapshot. + * Patch a snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param tags Resource tags + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, Map tags, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, tags), serviceCallback); + } + + /** + * Update a snapshot. + * Patch a snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param tags Resource tags + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SnapshotInner object + */ + public Observable updateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, Map tags) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName, tags).map(new Func1, SnapshotInner>() { + @Override + public SnapshotInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update a snapshot. + * Patch a snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param tags Resource tags + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SnapshotInner object + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, Map tags) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (snapshotName == null) { + throw new IllegalArgumentException("Parameter snapshotName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(tags); + SnapshotPatch body = new SnapshotPatch(); + body.withTags(tags); + return service.update(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, snapshotName, this.client.apiVersion(), this.client.acceptLanguage(), body, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse updateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Delete a snapshot. + * Delete snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + deleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).toBlocking().last().body(); + } + + /** + * Delete a snapshot. + * Delete snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName), serviceCallback); + } + + /** + * Delete a snapshot. + * Delete snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable deleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + return deleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a snapshot. + * Delete snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (snapshotName == null) { + throw new IllegalArgumentException("Parameter snapshotName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, snapshotName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Delete a snapshot. + * Delete snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).toBlocking().single().body(); + } + + /** + * Delete a snapshot. + * Delete snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName), serviceCallback); + } + + /** + * Delete a snapshot. + * Delete snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + return beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, snapshotName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a snapshot. + * Delete snapshot. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param snapshotName The name of the mount target + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String snapshotName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (snapshotName == null) { + throw new IllegalArgumentException("Parameter snapshotName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, snapshotName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumeImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumeImpl.java new file mode 100644 index 0000000000000..b1fab458bc3cd --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumeImpl.java @@ -0,0 +1,303 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.Volume; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.netapp.v2019_10_01.VolumePatch; +import com.microsoft.azure.management.netapp.v2019_10_01.ServiceLevel; +import com.microsoft.azure.management.netapp.v2019_10_01.VolumePropertiesExportPolicy; +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.VolumePropertiesDataProtection; +import java.util.Map; +import com.microsoft.azure.management.netapp.v2019_10_01.VolumePatchPropertiesExportPolicy; +import rx.functions.Func1; + +class VolumeImpl extends CreatableUpdatableImpl implements Volume, Volume.Definition, Volume.Update { + private final NetAppManager manager; + private String resourceGroupName; + private String accountName; + private String poolName; + private String volumeName; + private VolumePatch updateParameter; + + VolumeImpl(String name, NetAppManager manager) { + super(name, new VolumeInner()); + this.manager = manager; + // Set resource name + this.volumeName = name; + // + this.updateParameter = new VolumePatch(); + } + + VolumeImpl(VolumeInner inner, NetAppManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.volumeName = inner.name(); + // set resource ancestor and positional variables + this.resourceGroupName = IdParsingUtils.getValueFromIdByName(inner.id(), "resourceGroups"); + this.accountName = IdParsingUtils.getValueFromIdByName(inner.id(), "netAppAccounts"); + this.poolName = IdParsingUtils.getValueFromIdByName(inner.id(), "capacityPools"); + this.volumeName = IdParsingUtils.getValueFromIdByName(inner.id(), "volumes"); + // + this.updateParameter = new VolumePatch(); + } + + @Override + public NetAppManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + VolumesInner client = this.manager().inner().volumes(); + return client.createOrUpdateAsync(this.resourceGroupName, this.accountName, this.poolName, this.volumeName, this.inner()) + .map(new Func1() { + @Override + public VolumeInner call(VolumeInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + VolumesInner client = this.manager().inner().volumes(); + return client.updateAsync(this.resourceGroupName, this.accountName, this.poolName, this.volumeName, this.updateParameter) + .map(new Func1() { + @Override + public VolumeInner call(VolumeInner resource) { + resetCreateUpdateParameters(); + return resource; + } + }) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + VolumesInner client = this.manager().inner().volumes(); + return client.getAsync(this.resourceGroupName, this.accountName, this.poolName, this.volumeName); + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + private void resetCreateUpdateParameters() { + this.updateParameter = new VolumePatch(); + } + + @Override + public String baremetalTenantId() { + return this.inner().baremetalTenantId(); + } + + @Override + public String creationToken() { + return this.inner().creationToken(); + } + + @Override + public VolumePropertiesDataProtection dataProtection() { + return this.inner().dataProtection(); + } + + @Override + public VolumePropertiesExportPolicy exportPolicy() { + return this.inner().exportPolicy(); + } + + @Override + public String fileSystemId() { + return this.inner().fileSystemId(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public Boolean isRestoring() { + return this.inner().isRestoring(); + } + + @Override + public String location() { + return this.inner().location(); + } + + @Override + public Object mountTargets() { + return this.inner().mountTargets(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public List protocolTypes() { + return this.inner().protocolTypes(); + } + + @Override + public String provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public ServiceLevel serviceLevel() { + return this.inner().serviceLevel(); + } + + @Override + public String snapshotId() { + return this.inner().snapshotId(); + } + + @Override + public String subnetId() { + return this.inner().subnetId(); + } + + @Override + public Map tags() { + return this.inner().getTags(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public long usageThreshold() { + return this.inner().usageThreshold(); + } + + @Override + public String volumeType() { + return this.inner().volumeType(); + } + + @Override + public VolumeImpl withExistingCapacityPool(String resourceGroupName, String accountName, String poolName) { + this.resourceGroupName = resourceGroupName; + this.accountName = accountName; + this.poolName = poolName; + return this; + } + + @Override + public VolumeImpl withCreationToken(String creationToken) { + this.inner().withCreationToken(creationToken); + return this; + } + + @Override + public VolumeImpl withLocation(String location) { + this.inner().withLocation(location); + return this; + } + + @Override + public VolumeImpl withSubnetId(String subnetId) { + this.inner().withSubnetId(subnetId); + return this; + } + + @Override + public VolumeImpl withUsageThreshold(long usageThreshold) { + this.inner().withUsageThreshold(usageThreshold); + return this; + } + + @Override + public VolumeImpl withDataProtection(VolumePropertiesDataProtection dataProtection) { + this.inner().withDataProtection(dataProtection); + return this; + } + + @Override + public VolumeImpl withExportPolicy(VolumePropertiesExportPolicy exportPolicy) { + this.inner().withExportPolicy(exportPolicy); + return this; + } + + @Override + public VolumeImpl withIsRestoring(Boolean isRestoring) { + this.inner().withIsRestoring(isRestoring); + return this; + } + + @Override + public VolumeImpl withMountTargets(Object mountTargets) { + this.inner().withMountTargets(mountTargets); + return this; + } + + @Override + public VolumeImpl withProtocolTypes(List protocolTypes) { + this.inner().withProtocolTypes(protocolTypes); + return this; + } + + @Override + public VolumeImpl withSnapshotId(String snapshotId) { + this.inner().withSnapshotId(snapshotId); + return this; + } + + @Override + public VolumeImpl withVolumeType(String volumeType) { + this.inner().withVolumeType(volumeType); + return this; + } + + @Override + public VolumeImpl withExportPolicy(VolumePatchPropertiesExportPolicy exportPolicy) { + this.updateParameter.withExportPolicy(exportPolicy); + return this; + } + + @Override + public VolumeImpl withUsageThreshold(Long usageThreshold) { + this.updateParameter.withUsageThreshold(usageThreshold); + return this; + } + + @Override + public VolumeImpl withServiceLevel(ServiceLevel serviceLevel) { + if (isInCreateMode()) { + this.inner().withServiceLevel(serviceLevel); + } else { + this.updateParameter.withServiceLevel(serviceLevel); + } + return this; + } + + @Override + public VolumeImpl withTags(Map tags) { + if (isInCreateMode()) { + this.inner().withTags(tags); + } else { + this.updateParameter.withTags(tags); + } + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumeInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumeInner.java new file mode 100644 index 0000000000000..06fdd30099e6e --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumeInner.java @@ -0,0 +1,370 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.management.netapp.v2019_10_01.ServiceLevel; +import com.microsoft.azure.management.netapp.v2019_10_01.VolumePropertiesExportPolicy; +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.VolumePropertiesDataProtection; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.Resource; + +/** + * Volume resource. + */ +@JsonFlatten +public class VolumeInner extends Resource { + /** + * FileSystem ID. + * Unique FileSystem Identifier. + */ + @JsonProperty(value = "properties.fileSystemId", access = JsonProperty.Access.WRITE_ONLY) + private String fileSystemId; + + /** + * Creation Token or File Path. + * A unique file path for the volume. Used when creating mount targets. + */ + @JsonProperty(value = "properties.creationToken", required = true) + private String creationToken; + + /** + * serviceLevel. + * The service level of the file system. Possible values include: + * 'Standard', 'Premium', 'Ultra'. + */ + @JsonProperty(value = "properties.serviceLevel") + private ServiceLevel serviceLevel; + + /** + * usageThreshold. + * Maximum storage quota allowed for a file system in bytes. This is a soft + * quota used for alerting only. Minimum size is 100 GiB. Upper limit is + * 100TiB. Specified in bytes. + */ + @JsonProperty(value = "properties.usageThreshold", required = true) + private long usageThreshold; + + /** + * exportPolicy. + * Set of export policy rules. + */ + @JsonProperty(value = "properties.exportPolicy") + private VolumePropertiesExportPolicy exportPolicy; + + /** + * protocolTypes. + * Set of protocol types. + */ + @JsonProperty(value = "properties.protocolTypes") + private List protocolTypes; + + /** + * Azure lifecycle management. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * Snapshot ID. + * UUID v4 or resource identifier used to identify the Snapshot. + */ + @JsonProperty(value = "properties.snapshotId") + private String snapshotId; + + /** + * Baremetal Tenant ID. + * Unique Baremetal Tenant Identifier. + */ + @JsonProperty(value = "properties.baremetalTenantId", access = JsonProperty.Access.WRITE_ONLY) + private String baremetalTenantId; + + /** + * The Azure Resource URI for a delegated subnet. Must have the delegation + * Microsoft.NetApp/volumes. + */ + @JsonProperty(value = "properties.subnetId", required = true) + private String subnetId; + + /** + * mountTargets. + * List of mount targets. + */ + @JsonProperty(value = "properties.mountTargets") + private Object mountTargets; + + /** + * What type of volume is this. + */ + @JsonProperty(value = "properties.volumeType") + private String volumeType; + + /** + * DataProtection. + * DataProtection type volumes include an object containing details of the + * replication. + */ + @JsonProperty(value = "properties.dataProtection") + private VolumePropertiesDataProtection dataProtection; + + /** + * Restoring. + */ + @JsonProperty(value = "properties.isRestoring") + private Boolean isRestoring; + + /** + * Get unique FileSystem Identifier. + * + * @return the fileSystemId value + */ + public String fileSystemId() { + return this.fileSystemId; + } + + /** + * Get a unique file path for the volume. Used when creating mount targets. + * + * @return the creationToken value + */ + public String creationToken() { + return this.creationToken; + } + + /** + * Set a unique file path for the volume. Used when creating mount targets. + * + * @param creationToken the creationToken value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withCreationToken(String creationToken) { + this.creationToken = creationToken; + return this; + } + + /** + * Get the service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra'. + * + * @return the serviceLevel value + */ + public ServiceLevel serviceLevel() { + return this.serviceLevel; + } + + /** + * Set the service level of the file system. Possible values include: 'Standard', 'Premium', 'Ultra'. + * + * @param serviceLevel the serviceLevel value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withServiceLevel(ServiceLevel serviceLevel) { + this.serviceLevel = serviceLevel; + return this; + } + + /** + * Get maximum storage quota allowed for a file system in bytes. This is a soft quota used for alerting only. Minimum size is 100 GiB. Upper limit is 100TiB. Specified in bytes. + * + * @return the usageThreshold value + */ + public long usageThreshold() { + return this.usageThreshold; + } + + /** + * Set maximum storage quota allowed for a file system in bytes. This is a soft quota used for alerting only. Minimum size is 100 GiB. Upper limit is 100TiB. Specified in bytes. + * + * @param usageThreshold the usageThreshold value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withUsageThreshold(long usageThreshold) { + this.usageThreshold = usageThreshold; + return this; + } + + /** + * Get set of export policy rules. + * + * @return the exportPolicy value + */ + public VolumePropertiesExportPolicy exportPolicy() { + return this.exportPolicy; + } + + /** + * Set set of export policy rules. + * + * @param exportPolicy the exportPolicy value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withExportPolicy(VolumePropertiesExportPolicy exportPolicy) { + this.exportPolicy = exportPolicy; + return this; + } + + /** + * Get set of protocol types. + * + * @return the protocolTypes value + */ + public List protocolTypes() { + return this.protocolTypes; + } + + /** + * Set set of protocol types. + * + * @param protocolTypes the protocolTypes value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withProtocolTypes(List protocolTypes) { + this.protocolTypes = protocolTypes; + return this; + } + + /** + * Get azure lifecycle management. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + + /** + * Get uUID v4 or resource identifier used to identify the Snapshot. + * + * @return the snapshotId value + */ + public String snapshotId() { + return this.snapshotId; + } + + /** + * Set uUID v4 or resource identifier used to identify the Snapshot. + * + * @param snapshotId the snapshotId value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withSnapshotId(String snapshotId) { + this.snapshotId = snapshotId; + return this; + } + + /** + * Get unique Baremetal Tenant Identifier. + * + * @return the baremetalTenantId value + */ + public String baremetalTenantId() { + return this.baremetalTenantId; + } + + /** + * Get the Azure Resource URI for a delegated subnet. Must have the delegation Microsoft.NetApp/volumes. + * + * @return the subnetId value + */ + public String subnetId() { + return this.subnetId; + } + + /** + * Set the Azure Resource URI for a delegated subnet. Must have the delegation Microsoft.NetApp/volumes. + * + * @param subnetId the subnetId value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withSubnetId(String subnetId) { + this.subnetId = subnetId; + return this; + } + + /** + * Get list of mount targets. + * + * @return the mountTargets value + */ + public Object mountTargets() { + return this.mountTargets; + } + + /** + * Set list of mount targets. + * + * @param mountTargets the mountTargets value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withMountTargets(Object mountTargets) { + this.mountTargets = mountTargets; + return this; + } + + /** + * Get what type of volume is this. + * + * @return the volumeType value + */ + public String volumeType() { + return this.volumeType; + } + + /** + * Set what type of volume is this. + * + * @param volumeType the volumeType value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withVolumeType(String volumeType) { + this.volumeType = volumeType; + return this; + } + + /** + * Get dataProtection type volumes include an object containing details of the replication. + * + * @return the dataProtection value + */ + public VolumePropertiesDataProtection dataProtection() { + return this.dataProtection; + } + + /** + * Set dataProtection type volumes include an object containing details of the replication. + * + * @param dataProtection the dataProtection value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withDataProtection(VolumePropertiesDataProtection dataProtection) { + this.dataProtection = dataProtection; + return this; + } + + /** + * Get restoring. + * + * @return the isRestoring value + */ + public Boolean isRestoring() { + return this.isRestoring; + } + + /** + * Set restoring. + * + * @param isRestoring the isRestoring value to set + * @return the VolumeInner object itself. + */ + public VolumeInner withIsRestoring(Boolean isRestoring) { + this.isRestoring = isRestoring; + return this; + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumesImpl.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumesImpl.java new file mode 100644 index 0000000000000..6af18eaa7fd56 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumesImpl.java @@ -0,0 +1,122 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.netapp.v2019_10_01.Volumes; +import rx.Completable; +import rx.Observable; +import rx.functions.Func1; +import java.util.List; +import com.microsoft.azure.management.netapp.v2019_10_01.Volume; +import com.microsoft.azure.management.netapp.v2019_10_01.ReplicationStatus; + +class VolumesImpl extends WrapperImpl implements Volumes { + private final NetAppManager manager; + + VolumesImpl(NetAppManager manager) { + super(manager.inner().volumes()); + this.manager = manager; + } + + public NetAppManager manager() { + return this.manager; + } + + @Override + public VolumeImpl define(String name) { + return wrapModel(name); + } + + private VolumeImpl wrapModel(VolumeInner inner) { + return new VolumeImpl(inner, manager()); + } + + private VolumeImpl wrapModel(String name) { + return new VolumeImpl(name, this.manager()); + } + + @Override + public Completable breakReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + VolumesInner client = this.inner(); + return client.breakReplicationAsync(resourceGroupName, accountName, poolName, volumeName).toCompletable(); + } + + @Override + public Completable resyncReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + VolumesInner client = this.inner(); + return client.resyncReplicationAsync(resourceGroupName, accountName, poolName, volumeName).toCompletable(); + } + + @Override + public Completable deleteReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + VolumesInner client = this.inner(); + return client.deleteReplicationAsync(resourceGroupName, accountName, poolName, volumeName).toCompletable(); + } + + @Override + public Completable authorizeReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + VolumesInner client = this.inner(); + return client.authorizeReplicationAsync(resourceGroupName, accountName, poolName, volumeName).toCompletable(); + } + + @Override + public Observable listAsync(String resourceGroupName, String accountName, String poolName) { + VolumesInner client = this.inner(); + return client.listAsync(resourceGroupName, accountName, poolName) + .flatMap(new Func1, Observable>() { + @Override + public Observable call(List innerList) { + return Observable.from(innerList); + } + }) + .map(new Func1() { + @Override + public Volume call(VolumeInner inner) { + return wrapModel(inner); + } + }); + } + + @Override + public Observable getAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + VolumesInner client = this.inner(); + return client.getAsync(resourceGroupName, accountName, poolName, volumeName) + .flatMap(new Func1>() { + @Override + public Observable call(VolumeInner inner) { + if (inner == null) { + return Observable.empty(); + } else { + return Observable.just((Volume)wrapModel(inner)); + } + } + }); + } + + @Override + public Completable deleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + VolumesInner client = this.inner(); + return client.deleteAsync(resourceGroupName, accountName, poolName, volumeName).toCompletable(); + } + + @Override + public Observable replicationStatusMethodAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + VolumesInner client = this.inner(); + return client.replicationStatusMethodAsync(resourceGroupName, accountName, poolName, volumeName) + .map(new Func1() { + @Override + public ReplicationStatus call(ReplicationStatusInner inner) { + return new ReplicationStatusImpl(inner, manager()); + } + }); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumesInner.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumesInner.java new file mode 100644 index 0000000000000..5c213866dc848 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/VolumesInner.java @@ -0,0 +1,1452 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.CloudException; +import com.microsoft.azure.management.netapp.v2019_10_01.AuthorizeRequest; +import com.microsoft.azure.management.netapp.v2019_10_01.VolumePatch; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.PATCH; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Volumes. + */ +public class VolumesInner { + /** The Retrofit service to perform REST calls. */ + private VolumesService service; + /** The service client containing this operation class. */ + private AzureNetAppFilesManagementClientImpl client; + + /** + * Initializes an instance of VolumesInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public VolumesInner(Retrofit retrofit, AzureNetAppFilesManagementClientImpl client) { + this.service = retrofit.create(VolumesService.class); + this.client = client; + } + + /** + * The interface defining all the services for Volumes to be + * used by Retrofit to perform actually REST calls. + */ + interface VolumesService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes list" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes") + Observable> list(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes get" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}") + Observable> get(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes createOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}") + Observable> createOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Body VolumeInner body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes beginCreateOrUpdate" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}") + Observable> beginCreateOrUpdate(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Body VolumeInner body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes update" }) + @PATCH("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}") + Observable> update(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Body VolumePatch body, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes delete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", method = "DELETE", hasBody = true) + Observable> delete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes beginDelete" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}", method = "DELETE", hasBody = true) + Observable> beginDelete(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes breakReplication" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/breakReplication") + Observable> breakReplication(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes replicationStatusMethod" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/replicationStatus") + Observable> replicationStatusMethod(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes resyncReplication" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/resyncReplication") + Observable> resyncReplication(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes deleteReplication" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/deleteReplication") + Observable> deleteReplication(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.netapp.v2019_10_01.Volumes authorizeReplication" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.NetApp/netAppAccounts/{accountName}/capacityPools/{poolName}/volumes/{volumeName}/authorizeReplication") + Observable> authorizeReplication(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("accountName") String accountName, @Path("poolName") String poolName, @Path("volumeName") String volumeName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Body AuthorizeRequest body, @Header("User-Agent") String userAgent); + + } + + /** + * Describe all volumes. + * List all volumes within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException 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<VolumeInner> object if successful. + */ + public List list(String resourceGroupName, String accountName, String poolName) { + return listWithServiceResponseAsync(resourceGroupName, accountName, poolName).toBlocking().single().body(); + } + + /** + * Describe all volumes. + * List all volumes within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(String resourceGroupName, String accountName, String poolName, final ServiceCallback> serviceCallback) { + return ServiceFuture.fromResponse(listWithServiceResponseAsync(resourceGroupName, accountName, poolName), serviceCallback); + } + + /** + * Describe all volumes. + * List all volumes within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the List<VolumeInner> object + */ + public Observable> listAsync(String resourceGroupName, String accountName, String poolName) { + return listWithServiceResponseAsync(resourceGroupName, accountName, poolName).map(new Func1>, List>() { + @Override + public List call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Describe all volumes. + * List all volumes within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the List<VolumeInner> object + */ + public Observable>> listWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.list(this.client.subscriptionId(), resourceGroupName, accountName, poolName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + List items = null; + if (result.body() != null) { + items = result.body().items(); + } + ServiceResponse> clientResponse = new ServiceResponse>(items, result.response()); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., CloudException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Describe a volume. + * Get the details of the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VolumeInner object if successful. + */ + public VolumeInner get(String resourceGroupName, String accountName, String poolName, String volumeName) { + return getWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().single().body(); + } + + /** + * Describe a volume. + * Get the details of the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Describe a volume. + * Get the details of the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable to the VolumeInner object + */ + public Observable getAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return getWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1, VolumeInner>() { + @Override + public VolumeInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Describe a volume. + * Get the details of the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable to the VolumeInner object + */ + public Observable> getWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.get(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Create or Update a volume. + * Create or update the specified volume within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VolumeInner object if successful. + */ + public VolumeInner createOrUpdate(String resourceGroupName, String accountName, String poolName, String volumeName, VolumeInner body) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, body).toBlocking().last().body(); + } + + /** + * Create or Update a volume. + * Create or update the specified volume within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, VolumeInner body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, body), serviceCallback); + } + + /** + * Create or Update a volume. + * Create or update the specified volume within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable createOrUpdateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, VolumeInner body) { + return createOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, body).map(new Func1, VolumeInner>() { + @Override + public VolumeInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create or Update a volume. + * Create or update the specified volume within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + public Observable> createOrUpdateWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, VolumeInner body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + Observable> observable = service.createOrUpdate(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPutOrPatchResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Create or Update a volume. + * Create or update the specified volume within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VolumeInner object if successful. + */ + public VolumeInner beginCreateOrUpdate(String resourceGroupName, String accountName, String poolName, String volumeName, VolumeInner body) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, body).toBlocking().single().body(); + } + + /** + * Create or Update a volume. + * Create or update the specified volume within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginCreateOrUpdateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, VolumeInner body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, body), serviceCallback); + } + + /** + * Create or Update a volume. + * Create or update the specified volume within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VolumeInner object + */ + public Observable beginCreateOrUpdateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, VolumeInner body) { + return beginCreateOrUpdateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, body).map(new Func1, VolumeInner>() { + @Override + public VolumeInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Create or Update a volume. + * Create or update the specified volume within the capacity pool. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VolumeInner object + */ + public Observable> beginCreateOrUpdateWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, VolumeInner body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + return service.beginCreateOrUpdate(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginCreateOrUpdateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginCreateOrUpdateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Update a volume. + * Patch the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the VolumeInner object if successful. + */ + public VolumeInner update(String resourceGroupName, String accountName, String poolName, String volumeName, VolumePatch body) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, body).toBlocking().single().body(); + } + + /** + * Update a volume. + * Patch the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture updateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, VolumePatch body, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, body), serviceCallback); + } + + /** + * Update a volume. + * Patch the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VolumeInner object + */ + public Observable updateAsync(String resourceGroupName, String accountName, String poolName, String volumeName, VolumePatch body) { + return updateWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, body).map(new Func1, VolumeInner>() { + @Override + public VolumeInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Update a volume. + * Patch the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param body Volume object supplied in the body of the operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the VolumeInner object + */ + public Observable> updateWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, VolumePatch body) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (body == null) { + throw new IllegalArgumentException("Parameter body is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Validator.validate(body); + return service.update(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, body, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = updateDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse updateDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Delete a volume. + * Delete the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void delete(String resourceGroupName, String accountName, String poolName, String volumeName) { + deleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().last().body(); + } + + /** + * Delete a volume. + * Delete the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Delete a volume. + * Delete the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + public Observable deleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return deleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a volume. + * Delete the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable for the request + */ + public Observable> deleteWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + Observable> observable = service.delete(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()); + return client.getAzureClient().getPostOrDeleteResultAsync(observable, new TypeToken() { }.getType()); + } + + /** + * Delete a volume. + * Delete the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void beginDelete(String resourceGroupName, String accountName, String poolName, String volumeName) { + beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().single().body(); + } + + /** + * Delete a volume. + * Delete the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture beginDeleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Delete a volume. + * Delete the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable beginDeleteAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return beginDeleteWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete a volume. + * Delete the specified volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> beginDeleteWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.beginDelete(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = beginDeleteDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse beginDeleteDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Break volume replication. + * Break the replication connection on the destination volume. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void breakReplication(String resourceGroupName, String accountName, String poolName, String volumeName) { + breakReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().single().body(); + } + + /** + * Break volume replication. + * Break the replication connection on the destination volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture breakReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(breakReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Break volume replication. + * Break the replication connection on the destination volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable breakReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return breakReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Break volume replication. + * Break the replication connection on the destination volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> breakReplicationWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.breakReplication(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = breakReplicationDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse breakReplicationDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Get volume replication status. + * Get the status of the replication. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the ReplicationStatusInner object if successful. + */ + public ReplicationStatusInner replicationStatusMethod(String resourceGroupName, String accountName, String poolName, String volumeName) { + return replicationStatusMethodWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().single().body(); + } + + /** + * Get volume replication status. + * Get the status of the replication. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture replicationStatusMethodAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(replicationStatusMethodWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Get volume replication status. + * Get the status of the replication. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable to the ReplicationStatusInner object + */ + public Observable replicationStatusMethodAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return replicationStatusMethodWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1, ReplicationStatusInner>() { + @Override + public ReplicationStatusInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Get volume replication status. + * Get the status of the replication. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the observable to the ReplicationStatusInner object + */ + public Observable> replicationStatusMethodWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.replicationStatusMethod(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = replicationStatusMethodDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse replicationStatusMethodDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Resync volume replication. + * Resync the connection on the destination volume. If the operation is ran on the source volume it will reverse-resync the connection and sync from source to destination. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void resyncReplication(String resourceGroupName, String accountName, String poolName, String volumeName) { + resyncReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().single().body(); + } + + /** + * Resync volume replication. + * Resync the connection on the destination volume. If the operation is ran on the source volume it will reverse-resync the connection and sync from source to destination. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture resyncReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(resyncReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Resync volume replication. + * Resync the connection on the destination volume. If the operation is ran on the source volume it will reverse-resync the connection and sync from source to destination. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable resyncReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return resyncReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Resync volume replication. + * Resync the connection on the destination volume. If the operation is ran on the source volume it will reverse-resync the connection and sync from source to destination. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> resyncReplicationWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.resyncReplication(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = resyncReplicationDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse resyncReplicationDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Delete volume replication. + * Delete the replication connection on the destination volume, and send release to the source replication. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void deleteReplication(String resourceGroupName, String accountName, String poolName, String volumeName) { + deleteReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().single().body(); + } + + /** + * Delete volume replication. + * Delete the replication connection on the destination volume, and send release to the source replication. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Delete volume replication. + * Delete the replication connection on the destination volume, and send release to the source replication. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable deleteReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return deleteReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Delete volume replication. + * Delete the replication connection on the destination volume, and send release to the source replication. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> deleteReplicationWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + return service.deleteReplication(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteReplicationDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse deleteReplicationDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + + /** + * Authorize source volume replication. + * Authorize the replication connection on the source volume. + * + * @param resourceGroupName The name of the resource group. + * @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 CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void authorizeReplication(String resourceGroupName, String accountName, String poolName, String volumeName) { + authorizeReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).toBlocking().single().body(); + } + + /** + * Authorize source volume replication. + * Authorize the replication connection on the source volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture authorizeReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(authorizeReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName), serviceCallback); + } + + /** + * Authorize source volume replication. + * Authorize the replication connection on the source volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable authorizeReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + return authorizeReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Authorize source volume replication. + * Authorize the replication connection on the source volume. + * + * @param resourceGroupName The name of the resource group. + * @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 + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> authorizeReplicationWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + final String remoteVolumeResourceId = null; + AuthorizeRequest body = new AuthorizeRequest(); + body.withRemoteVolumeResourceId(null); + return service.authorizeReplication(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), body, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = authorizeReplicationDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Authorize source volume replication. + * Authorize the replication connection on the source volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param remoteVolumeResourceId Resource id + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws CloudException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + */ + public void authorizeReplication(String resourceGroupName, String accountName, String poolName, String volumeName, String remoteVolumeResourceId) { + authorizeReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, remoteVolumeResourceId).toBlocking().single().body(); + } + + /** + * Authorize source volume replication. + * Authorize the replication connection on the source volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param remoteVolumeResourceId Resource id + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture authorizeReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String remoteVolumeResourceId, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(authorizeReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, remoteVolumeResourceId), serviceCallback); + } + + /** + * Authorize source volume replication. + * Authorize the replication connection on the source volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param remoteVolumeResourceId Resource id + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable authorizeReplicationAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String remoteVolumeResourceId) { + return authorizeReplicationWithServiceResponseAsync(resourceGroupName, accountName, poolName, volumeName, remoteVolumeResourceId).map(new Func1, Void>() { + @Override + public Void call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Authorize source volume replication. + * Authorize the replication connection on the source volume. + * + * @param resourceGroupName The name of the resource group. + * @param accountName The name of the NetApp account + * @param poolName The name of the capacity pool + * @param volumeName The name of the volume + * @param remoteVolumeResourceId Resource id + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceResponse} object if successful. + */ + public Observable> authorizeReplicationWithServiceResponseAsync(String resourceGroupName, String accountName, String poolName, String volumeName, String remoteVolumeResourceId) { + if (this.client.subscriptionId() == null) { + throw new IllegalArgumentException("Parameter this.client.subscriptionId() is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (accountName == null) { + throw new IllegalArgumentException("Parameter accountName is required and cannot be null."); + } + if (poolName == null) { + throw new IllegalArgumentException("Parameter poolName is required and cannot be null."); + } + if (volumeName == null) { + throw new IllegalArgumentException("Parameter volumeName is required and cannot be null."); + } + if (this.client.apiVersion() == null) { + throw new IllegalArgumentException("Parameter this.client.apiVersion() is required and cannot be null."); + } + AuthorizeRequest body = new AuthorizeRequest(); + body.withRemoteVolumeResourceId(remoteVolumeResourceId); + return service.authorizeReplication(this.client.subscriptionId(), resourceGroupName, accountName, poolName, volumeName, this.client.apiVersion(), this.client.acceptLanguage(), body, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = authorizeReplicationDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse authorizeReplicationDelegate(Response response) throws CloudException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(202, new TypeToken() { }.getType()) + .registerError(CloudException.class) + .build(response); + } + +} diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/package-info.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/package-info.java new file mode 100644 index 0000000000000..be084301514b6 --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/implementation/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the implementation classes for AzureNetAppFilesManagementClient. + * Microsoft NetApp Azure Resource Provider specification. + */ +package com.microsoft.azure.management.netapp.v2019_10_01.implementation; diff --git a/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/package-info.java b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/package-info.java new file mode 100644 index 0000000000000..ce15ec7708a2c --- /dev/null +++ b/sdk/netapp/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/netapp/v2019_10_01/package-info.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the classes for AzureNetAppFilesManagementClient. + * Microsoft NetApp Azure Resource Provider specification. + */ +package com.microsoft.azure.management.netapp.v2019_10_01; diff --git a/sdk/netapp/pom.mgmt.xml b/sdk/netapp/pom.mgmt.xml index 7004bf4f6e340..133c121ef4e77 100644 --- a/sdk/netapp/pom.mgmt.xml +++ b/sdk/netapp/pom.mgmt.xml @@ -14,5 +14,6 @@ mgmt-v2019_06_01 mgmt-v2019_07_01 mgmt-v2019_08_01 + mgmt-v2019_10_01 diff --git a/sdk/policyinsights/mgmt-v2019_10_01/pom.xml b/sdk/policyinsights/mgmt-v2019_10_01/pom.xml new file mode 100644 index 0000000000000..025cea421db09 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/pom.xml @@ -0,0 +1,135 @@ + + + 4.0.0 + com.microsoft.azure.policyinsights.v2019_10_01 + + com.microsoft.azure + azure-arm-parent + 1.1.0 + ../../../pom.management.xml + + azure-mgmt-policyinsights + 1.0.0-beta + jar + Microsoft Azure SDK for PolicyInsights Management + This package contains Microsoft PolicyInsights Management SDK. + https://github.com/Azure/azure-sdk-for-java + + + The MIT License (MIT) + http://opensource.org/licenses/MIT + repo + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + UTF-8 + + + + + microsoft + Microsoft + + + + + com.microsoft.azure + azure-client-runtime + + + com.microsoft.azure + azure-arm-client-runtime + + + junit + junit + test + + + com.microsoft.azure + azure-client-authentication + test + + + com.microsoft.azure + azure-mgmt-resources + test + + + com.microsoft.azure + azure-arm-client-runtime + test-jar + test + + 1.6.5 + + + + + + org.apache.maven.plugins + maven-jar-plugin + + + + true + true + + + + + + org.codehaus.mojo + build-helper-maven-plugin + + + org.apache.maven.plugins + maven-compiler-plugin + 3.1 + + 1.7 + 1.7 + + + com.microsoft.azure.management.apigeneration.LangDefinitionProcessor + + + true + true + + true + true + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + *.implementation.*;*.utils.*;com.microsoft.schemas._2003._10.serialization;*.blob.core.search + + + /** +
* Copyright (c) Microsoft Corporation. All rights reserved. +
* Licensed under the MIT License. See License.txt in the project root for +
* license information. +
*/ + ]]> +
+
+
+
+
+
diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ComplianceDetail.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ComplianceDetail.java new file mode 100644 index 0000000000000..e63f4b7190e24 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ComplianceDetail.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The compliance state rollup. + */ +public class ComplianceDetail { + /** + * The compliance state. + */ + @JsonProperty(value = "complianceState") + private String complianceState; + + /** + * Summarized count value for this compliance state. + */ + @JsonProperty(value = "count") + private Integer count; + + /** + * Get the compliance state. + * + * @return the complianceState value + */ + public String complianceState() { + return this.complianceState; + } + + /** + * Set the compliance state. + * + * @param complianceState the complianceState value to set + * @return the ComplianceDetail object itself. + */ + public ComplianceDetail withComplianceState(String complianceState) { + this.complianceState = complianceState; + return this; + } + + /** + * Get summarized count value for this compliance state. + * + * @return the count value + */ + public Integer count() { + return this.count; + } + + /** + * Set summarized count value for this compliance state. + * + * @param count the count value to set + * @return the ComplianceDetail object itself. + */ + public ComplianceDetail withCount(Integer count) { + this.count = count; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ErrorDefinition.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ErrorDefinition.java new file mode 100644 index 0000000000000..a5b6f01aea269 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ErrorDefinition.java @@ -0,0 +1,94 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Error definition. + */ +public class ErrorDefinition { + /** + * Service specific error code which serves as the substatus for the HTTP + * error code. + */ + @JsonProperty(value = "code", access = JsonProperty.Access.WRITE_ONLY) + private String code; + + /** + * Description of the error. + */ + @JsonProperty(value = "message", access = JsonProperty.Access.WRITE_ONLY) + private String message; + + /** + * The target of the error. + */ + @JsonProperty(value = "target", access = JsonProperty.Access.WRITE_ONLY) + private String target; + + /** + * Internal error details. + */ + @JsonProperty(value = "details", access = JsonProperty.Access.WRITE_ONLY) + private List details; + + /** + * Additional scenario specific error details. + */ + @JsonProperty(value = "additionalInfo", access = JsonProperty.Access.WRITE_ONLY) + private List additionalInfo; + + /** + * Get service specific error code which serves as the substatus for the HTTP error code. + * + * @return the code value + */ + public String code() { + return this.code; + } + + /** + * Get description of the error. + * + * @return the message value + */ + public String message() { + return this.message; + } + + /** + * Get the target of the error. + * + * @return the target value + */ + public String target() { + return this.target; + } + + /** + * Get internal error details. + * + * @return the details value + */ + public List details() { + return this.details; + } + + /** + * Get additional scenario specific error details. + * + * @return the additionalInfo value + */ + public List additionalInfo() { + return this.additionalInfo; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ErrorResponse.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ErrorResponse.java new file mode 100644 index 0000000000000..95003b40fbac6 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ErrorResponse.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Error response. + */ +public class ErrorResponse { + /** + * The error details. + */ + @JsonProperty(value = "error") + private ErrorDefinition error; + + /** + * Get the error details. + * + * @return the error value + */ + public ErrorDefinition error() { + return this.error; + } + + /** + * Set the error details. + * + * @param error the error value to set + * @return the ErrorResponse object itself. + */ + public ErrorResponse withError(ErrorDefinition error) { + this.error = error; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ErrorResponseException.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ErrorResponseException.java new file mode 100644 index 0000000000000..98bdcfc26ccc8 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ErrorResponseException.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.rest.RestException; +import okhttp3.ResponseBody; +import retrofit2.Response; + +/** + * Exception thrown for an invalid response with ErrorResponse information. + */ +public class ErrorResponseException extends RestException { + /** + * Initializes a new instance of the ErrorResponseException class. + * + * @param message the exception message or the response content if a message is not available + * @param response the HTTP response + */ + public ErrorResponseException(final String message, final Response response) { + super(message, response); + } + + /** + * Initializes a new instance of the ErrorResponseException class. + * + * @param message the exception message or the response content if a message is not available + * @param response the HTTP response + * @param body the deserialized response body + */ + public ErrorResponseException(final String message, final Response response, final ErrorResponse body) { + super(message, response, body); + } + + @Override + public ErrorResponse body() { + return (ErrorResponse) super.body(); + } +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ExpressionEvaluationDetails.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ExpressionEvaluationDetails.java new file mode 100644 index 0000000000000..8baf3c4b93f12 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ExpressionEvaluationDetails.java @@ -0,0 +1,173 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Evaluation details of policy language expressions. + */ +public class ExpressionEvaluationDetails { + /** + * Evaluation result. + */ + @JsonProperty(value = "result") + private String result; + + /** + * Expression evaluated. + */ + @JsonProperty(value = "expression") + private String expression; + + /** + * Property path if the expression is a field or an alias. + */ + @JsonProperty(value = "path") + private String path; + + /** + * Value of the expression. + */ + @JsonProperty(value = "expressionValue") + private Object expressionValue; + + /** + * Target value to be compared with the expression value. + */ + @JsonProperty(value = "targetValue") + private Object targetValue; + + /** + * Operator to compare the expression value and the target value. + */ + @JsonProperty(value = "operator") + private String operator; + + /** + * Get evaluation result. + * + * @return the result value + */ + public String result() { + return this.result; + } + + /** + * Set evaluation result. + * + * @param result the result value to set + * @return the ExpressionEvaluationDetails object itself. + */ + public ExpressionEvaluationDetails withResult(String result) { + this.result = result; + return this; + } + + /** + * Get expression evaluated. + * + * @return the expression value + */ + public String expression() { + return this.expression; + } + + /** + * Set expression evaluated. + * + * @param expression the expression value to set + * @return the ExpressionEvaluationDetails object itself. + */ + public ExpressionEvaluationDetails withExpression(String expression) { + this.expression = expression; + return this; + } + + /** + * Get property path if the expression is a field or an alias. + * + * @return the path value + */ + public String path() { + return this.path; + } + + /** + * Set property path if the expression is a field or an alias. + * + * @param path the path value to set + * @return the ExpressionEvaluationDetails object itself. + */ + public ExpressionEvaluationDetails withPath(String path) { + this.path = path; + return this; + } + + /** + * Get value of the expression. + * + * @return the expressionValue value + */ + public Object expressionValue() { + return this.expressionValue; + } + + /** + * Set value of the expression. + * + * @param expressionValue the expressionValue value to set + * @return the ExpressionEvaluationDetails object itself. + */ + public ExpressionEvaluationDetails withExpressionValue(Object expressionValue) { + this.expressionValue = expressionValue; + return this; + } + + /** + * Get target value to be compared with the expression value. + * + * @return the targetValue value + */ + public Object targetValue() { + return this.targetValue; + } + + /** + * Set target value to be compared with the expression value. + * + * @param targetValue the targetValue value to set + * @return the ExpressionEvaluationDetails object itself. + */ + public ExpressionEvaluationDetails withTargetValue(Object targetValue) { + this.targetValue = targetValue; + return this; + } + + /** + * Get operator to compare the expression value and the target value. + * + * @return the operator value + */ + public String operator() { + return this.operator; + } + + /** + * Set operator to compare the expression value and the target value. + * + * @param operator the operator value to set + * @return the ExpressionEvaluationDetails object itself. + */ + public ExpressionEvaluationDetails withOperator(String operator) { + this.operator = operator; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/IfNotExistsEvaluationDetails.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/IfNotExistsEvaluationDetails.java new file mode 100644 index 0000000000000..8bc664a8cbae9 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/IfNotExistsEvaluationDetails.java @@ -0,0 +1,70 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Evaluation details of IfNotExists effect. + */ +public class IfNotExistsEvaluationDetails { + /** + * ID of the last evaluated resource for IfNotExists effect. + */ + @JsonProperty(value = "resourceId") + private String resourceId; + + /** + * Total number of resources to which the existence condition is + * applicable. + */ + @JsonProperty(value = "totalResources") + private Integer totalResources; + + /** + * Get iD of the last evaluated resource for IfNotExists effect. + * + * @return the resourceId value + */ + public String resourceId() { + return this.resourceId; + } + + /** + * Set iD of the last evaluated resource for IfNotExists effect. + * + * @param resourceId the resourceId value to set + * @return the IfNotExistsEvaluationDetails object itself. + */ + public IfNotExistsEvaluationDetails withResourceId(String resourceId) { + this.resourceId = resourceId; + return this; + } + + /** + * Get total number of resources to which the existence condition is applicable. + * + * @return the totalResources value + */ + public Integer totalResources() { + return this.totalResources; + } + + /** + * Set total number of resources to which the existence condition is applicable. + * + * @param totalResources the totalResources value to set + * @return the IfNotExistsEvaluationDetails object itself. + */ + public IfNotExistsEvaluationDetails withTotalResources(Integer totalResources) { + this.totalResources = totalResources; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/OperationDisplay.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/OperationDisplay.java new file mode 100644 index 0000000000000..2f634c651e19f --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/OperationDisplay.java @@ -0,0 +1,121 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Display metadata associated with the operation. + */ +public class OperationDisplay { + /** + * Resource provider name. + */ + @JsonProperty(value = "provider") + private String provider; + + /** + * Resource name on which the operation is performed. + */ + @JsonProperty(value = "resource") + private String resource; + + /** + * Operation name. + */ + @JsonProperty(value = "operation") + private String operation; + + /** + * Operation description. + */ + @JsonProperty(value = "description") + private String description; + + /** + * Get resource provider name. + * + * @return the provider value + */ + public String provider() { + return this.provider; + } + + /** + * Set resource provider name. + * + * @param provider the provider value to set + * @return the OperationDisplay object itself. + */ + public OperationDisplay withProvider(String provider) { + this.provider = provider; + return this; + } + + /** + * Get resource name on which the operation is performed. + * + * @return the resource value + */ + public String resource() { + return this.resource; + } + + /** + * Set resource name on which the operation is performed. + * + * @param resource the resource value to set + * @return the OperationDisplay object itself. + */ + public OperationDisplay withResource(String resource) { + this.resource = resource; + return this; + } + + /** + * Get operation name. + * + * @return the operation value + */ + public String operation() { + return this.operation; + } + + /** + * Set operation name. + * + * @param operation the operation value to set + * @return the OperationDisplay object itself. + */ + public OperationDisplay withOperation(String operation) { + this.operation = operation; + return this; + } + + /** + * Get operation description. + * + * @return the description value + */ + public String description() { + return this.description; + } + + /** + * Set operation description. + * + * @param description the description value to set + * @return the OperationDisplay object itself. + */ + public OperationDisplay withDescription(String description) { + this.description = description; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Operations.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Operations.java new file mode 100644 index 0000000000000..eea298ebfc481 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Operations.java @@ -0,0 +1,27 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import rx.Observable; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.OperationsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Operations. + */ +public interface Operations extends HasInner { + /** + * Lists available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/OperationsListResults.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/OperationsListResults.java new file mode 100644 index 0000000000000..ddfada5b0ab23 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/OperationsListResults.java @@ -0,0 +1,32 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyInsightsManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.OperationsListResultsInner; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.OperationInner; +import java.util.List; + +/** + * Type representing OperationsListResults. + */ +public interface OperationsListResults extends HasInner, HasManager { + /** + * @return the odatacount value. + */ + Integer odatacount(); + + /** + * @return the value value. + */ + List value(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyAssignmentSummary.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyAssignmentSummary.java new file mode 100644 index 0000000000000..3dff9e146ac04 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyAssignmentSummary.java @@ -0,0 +1,148 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Policy assignment summary. + */ +public class PolicyAssignmentSummary { + /** + * Policy assignment ID. + */ + @JsonProperty(value = "policyAssignmentId") + private String policyAssignmentId; + + /** + * Policy set definition ID, if the policy assignment is for a policy set. + */ + @JsonProperty(value = "policySetDefinitionId") + private String policySetDefinitionId; + + /** + * Compliance summary for the policy assignment. + */ + @JsonProperty(value = "results") + private SummaryResults results; + + /** + * Policy definitions summary. + */ + @JsonProperty(value = "policyDefinitions") + private List policyDefinitions; + + /** + * Policy definition group summary. + */ + @JsonProperty(value = "policyGroups") + private List policyGroups; + + /** + * Get policy assignment ID. + * + * @return the policyAssignmentId value + */ + public String policyAssignmentId() { + return this.policyAssignmentId; + } + + /** + * Set policy assignment ID. + * + * @param policyAssignmentId the policyAssignmentId value to set + * @return the PolicyAssignmentSummary object itself. + */ + public PolicyAssignmentSummary withPolicyAssignmentId(String policyAssignmentId) { + this.policyAssignmentId = policyAssignmentId; + return this; + } + + /** + * Get policy set definition ID, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionId value + */ + public String policySetDefinitionId() { + return this.policySetDefinitionId; + } + + /** + * Set policy set definition ID, if the policy assignment is for a policy set. + * + * @param policySetDefinitionId the policySetDefinitionId value to set + * @return the PolicyAssignmentSummary object itself. + */ + public PolicyAssignmentSummary withPolicySetDefinitionId(String policySetDefinitionId) { + this.policySetDefinitionId = policySetDefinitionId; + return this; + } + + /** + * Get compliance summary for the policy assignment. + * + * @return the results value + */ + public SummaryResults results() { + return this.results; + } + + /** + * Set compliance summary for the policy assignment. + * + * @param results the results value to set + * @return the PolicyAssignmentSummary object itself. + */ + public PolicyAssignmentSummary withResults(SummaryResults results) { + this.results = results; + return this; + } + + /** + * Get policy definitions summary. + * + * @return the policyDefinitions value + */ + public List policyDefinitions() { + return this.policyDefinitions; + } + + /** + * Set policy definitions summary. + * + * @param policyDefinitions the policyDefinitions value to set + * @return the PolicyAssignmentSummary object itself. + */ + public PolicyAssignmentSummary withPolicyDefinitions(List policyDefinitions) { + this.policyDefinitions = policyDefinitions; + return this; + } + + /** + * Get policy definition group summary. + * + * @return the policyGroups value + */ + public List policyGroups() { + return this.policyGroups; + } + + /** + * Set policy definition group summary. + * + * @param policyGroups the policyGroups value to set + * @return the PolicyAssignmentSummary object itself. + */ + public PolicyAssignmentSummary withPolicyGroups(List policyGroups) { + this.policyGroups = policyGroups; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyDefinitionSummary.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyDefinitionSummary.java new file mode 100644 index 0000000000000..9a5f444cec780 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyDefinitionSummary.java @@ -0,0 +1,148 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Policy definition summary. + */ +public class PolicyDefinitionSummary { + /** + * Policy definition ID. + */ + @JsonProperty(value = "policyDefinitionId") + private String policyDefinitionId; + + /** + * Policy definition reference ID. + */ + @JsonProperty(value = "policyDefinitionReferenceId") + private String policyDefinitionReferenceId; + + /** + * Policy definition group names. + */ + @JsonProperty(value = "policyDefinitionGroupNames") + private List policyDefinitionGroupNames; + + /** + * Policy effect, i.e. policy definition action. + */ + @JsonProperty(value = "effect") + private String effect; + + /** + * Compliance summary for the policy definition. + */ + @JsonProperty(value = "results") + private SummaryResults results; + + /** + * Get policy definition ID. + * + * @return the policyDefinitionId value + */ + public String policyDefinitionId() { + return this.policyDefinitionId; + } + + /** + * Set policy definition ID. + * + * @param policyDefinitionId the policyDefinitionId value to set + * @return the PolicyDefinitionSummary object itself. + */ + public PolicyDefinitionSummary withPolicyDefinitionId(String policyDefinitionId) { + this.policyDefinitionId = policyDefinitionId; + return this; + } + + /** + * Get policy definition reference ID. + * + * @return the policyDefinitionReferenceId value + */ + public String policyDefinitionReferenceId() { + return this.policyDefinitionReferenceId; + } + + /** + * Set policy definition reference ID. + * + * @param policyDefinitionReferenceId the policyDefinitionReferenceId value to set + * @return the PolicyDefinitionSummary object itself. + */ + public PolicyDefinitionSummary withPolicyDefinitionReferenceId(String policyDefinitionReferenceId) { + this.policyDefinitionReferenceId = policyDefinitionReferenceId; + return this; + } + + /** + * Get policy definition group names. + * + * @return the policyDefinitionGroupNames value + */ + public List policyDefinitionGroupNames() { + return this.policyDefinitionGroupNames; + } + + /** + * Set policy definition group names. + * + * @param policyDefinitionGroupNames the policyDefinitionGroupNames value to set + * @return the PolicyDefinitionSummary object itself. + */ + public PolicyDefinitionSummary withPolicyDefinitionGroupNames(List policyDefinitionGroupNames) { + this.policyDefinitionGroupNames = policyDefinitionGroupNames; + return this; + } + + /** + * Get policy effect, i.e. policy definition action. + * + * @return the effect value + */ + public String effect() { + return this.effect; + } + + /** + * Set policy effect, i.e. policy definition action. + * + * @param effect the effect value to set + * @return the PolicyDefinitionSummary object itself. + */ + public PolicyDefinitionSummary withEffect(String effect) { + this.effect = effect; + return this; + } + + /** + * Get compliance summary for the policy definition. + * + * @return the results value + */ + public SummaryResults results() { + return this.results; + } + + /** + * Set compliance summary for the policy definition. + * + * @param results the results value to set + * @return the PolicyDefinitionSummary object itself. + */ + public PolicyDefinitionSummary withResults(SummaryResults results) { + this.results = results; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyDetails.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyDetails.java new file mode 100644 index 0000000000000..114c1b3270b80 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyDetails.java @@ -0,0 +1,107 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The policy details. + */ +public class PolicyDetails { + /** + * The ID of the policy definition. + */ + @JsonProperty(value = "policyDefinitionId", access = JsonProperty.Access.WRITE_ONLY) + private String policyDefinitionId; + + /** + * The ID of the policy assignment. + */ + @JsonProperty(value = "policyAssignmentId", access = JsonProperty.Access.WRITE_ONLY) + private String policyAssignmentId; + + /** + * The display name of the policy assignment. + */ + @JsonProperty(value = "policyAssignmentDisplayName", access = JsonProperty.Access.WRITE_ONLY) + private String policyAssignmentDisplayName; + + /** + * The scope of the policy assignment. + */ + @JsonProperty(value = "policyAssignmentScope", access = JsonProperty.Access.WRITE_ONLY) + private String policyAssignmentScope; + + /** + * The ID of the policy set definition. + */ + @JsonProperty(value = "policySetDefinitionId", access = JsonProperty.Access.WRITE_ONLY) + private String policySetDefinitionId; + + /** + * The policy definition reference ID within the policy set definition. + */ + @JsonProperty(value = "policyDefinitionReferenceId", access = JsonProperty.Access.WRITE_ONLY) + private String policyDefinitionReferenceId; + + /** + * Get the ID of the policy definition. + * + * @return the policyDefinitionId value + */ + public String policyDefinitionId() { + return this.policyDefinitionId; + } + + /** + * Get the ID of the policy assignment. + * + * @return the policyAssignmentId value + */ + public String policyAssignmentId() { + return this.policyAssignmentId; + } + + /** + * Get the display name of the policy assignment. + * + * @return the policyAssignmentDisplayName value + */ + public String policyAssignmentDisplayName() { + return this.policyAssignmentDisplayName; + } + + /** + * Get the scope of the policy assignment. + * + * @return the policyAssignmentScope value + */ + public String policyAssignmentScope() { + return this.policyAssignmentScope; + } + + /** + * Get the ID of the policy set definition. + * + * @return the policySetDefinitionId value + */ + public String policySetDefinitionId() { + return this.policySetDefinitionId; + } + + /** + * Get the policy definition reference ID within the policy set definition. + * + * @return the policyDefinitionReferenceId value + */ + public String policyDefinitionReferenceId() { + return this.policyDefinitionReferenceId; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyEvaluationDetails.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyEvaluationDetails.java new file mode 100644 index 0000000000000..f98d77e1fe9ff --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyEvaluationDetails.java @@ -0,0 +1,70 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Policy evaluation details. + */ +public class PolicyEvaluationDetails { + /** + * Details of the evaluated expressions. + */ + @JsonProperty(value = "evaluatedExpressions") + private List evaluatedExpressions; + + /** + * Evaluation details of IfNotExists effect. + */ + @JsonProperty(value = "ifNotExistsDetails") + private IfNotExistsEvaluationDetails ifNotExistsDetails; + + /** + * Get details of the evaluated expressions. + * + * @return the evaluatedExpressions value + */ + public List evaluatedExpressions() { + return this.evaluatedExpressions; + } + + /** + * Set details of the evaluated expressions. + * + * @param evaluatedExpressions the evaluatedExpressions value to set + * @return the PolicyEvaluationDetails object itself. + */ + public PolicyEvaluationDetails withEvaluatedExpressions(List evaluatedExpressions) { + this.evaluatedExpressions = evaluatedExpressions; + return this; + } + + /** + * Get evaluation details of IfNotExists effect. + * + * @return the ifNotExistsDetails value + */ + public IfNotExistsEvaluationDetails ifNotExistsDetails() { + return this.ifNotExistsDetails; + } + + /** + * Set evaluation details of IfNotExists effect. + * + * @param ifNotExistsDetails the ifNotExistsDetails value to set + * @return the PolicyEvaluationDetails object itself. + */ + public PolicyEvaluationDetails withIfNotExistsDetails(IfNotExistsEvaluationDetails ifNotExistsDetails) { + this.ifNotExistsDetails = ifNotExistsDetails; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyEvents.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyEvents.java new file mode 100644 index 0000000000000..1d788d1cddad8 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyEvents.java @@ -0,0 +1,104 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import rx.Observable; + +/** + * Type representing PolicyEvents. + */ +public interface PolicyEvents { + /** + * Queries policy events for the resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForManagementGroupAsync(String managementGroupName); + + /** + * Queries policy events for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForSubscriptionAsync(String subscriptionId); + + /** + * Queries policy events for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForResourceGroupAsync(String subscriptionId, String resourceGroupName); + + /** + * Queries policy events for the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForResourceAsync(String resourceId); + + /** + * Queries policy events for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName); + + /** + * Queries policy events for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName); + + /** + * Queries policy events for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName); + + /** + * Queries policy events for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName); + + /** + * Gets OData metadata XML document. + * + * @param scope A valid scope, i.e. management group, subscription, resource group, or resource ID. Scope used has no effect on metadata returned. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getMetadataAsync(String scope); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyEventsQueryResults.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyEventsQueryResults.java new file mode 100644 index 0000000000000..a5eeaa447b52b --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyEventsQueryResults.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyInsightsManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyEventsQueryResultsInner; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyEventInner; +import java.util.List; + +/** + * Type representing PolicyEventsQueryResults. + */ +public interface PolicyEventsQueryResults extends HasInner, HasManager { + /** + * @return the odatacontext value. + */ + String odatacontext(); + + /** + * @return the odatacount value. + */ + Integer odatacount(); + + /** + * @return the value value. + */ + List value(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyGroupSummary.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyGroupSummary.java new file mode 100644 index 0000000000000..6418be1b13b93 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyGroupSummary.java @@ -0,0 +1,69 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Policy definition group summary. + */ +public class PolicyGroupSummary { + /** + * Policy group name. + */ + @JsonProperty(value = "policyGroupName") + private String policyGroupName; + + /** + * Compliance summary for the policy definition group. + */ + @JsonProperty(value = "results") + private SummaryResults results; + + /** + * Get policy group name. + * + * @return the policyGroupName value + */ + public String policyGroupName() { + return this.policyGroupName; + } + + /** + * Set policy group name. + * + * @param policyGroupName the policyGroupName value to set + * @return the PolicyGroupSummary object itself. + */ + public PolicyGroupSummary withPolicyGroupName(String policyGroupName) { + this.policyGroupName = policyGroupName; + return this; + } + + /** + * Get compliance summary for the policy definition group. + * + * @return the results value + */ + public SummaryResults results() { + return this.results; + } + + /** + * Set compliance summary for the policy definition group. + * + * @param results the results value to set + * @return the PolicyGroupSummary object itself. + */ + public PolicyGroupSummary withResults(SummaryResults results) { + this.results = results; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyMetadata.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyMetadata.java new file mode 100644 index 0000000000000..ed68ee192e237 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyMetadata.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyInsightsManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyMetadataInner; + +/** + * Type representing PolicyMetadata. + */ +public interface PolicyMetadata extends HasInner, HasManager { + /** + * @return the additionalContentUrl value. + */ + String additionalContentUrl(); + + /** + * @return the category value. + */ + String category(); + + /** + * @return the description value. + */ + String description(); + + /** + * @return the id value. + */ + String id(); + + /** + * @return the metadata value. + */ + Object metadata(); + + /** + * @return the metadataId value. + */ + String metadataId(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the owner value. + */ + String owner(); + + /** + * @return the requirements value. + */ + String requirements(); + + /** + * @return the title value. + */ + String title(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyMetadatas.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyMetadatas.java new file mode 100644 index 0000000000000..7b395ce4d94a0 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyMetadatas.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import rx.Observable; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyMetadatasInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing PolicyMetadatas. + */ +public interface PolicyMetadatas extends HasInner { + /** + * Get policy metadata resource. + * + * @param resourceName The name of the policy metadata resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getResourceAsync(String resourceName); + + /** + * Get a list of the policy metadata resources. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyStates.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyStates.java new file mode 100644 index 0000000000000..91c835ae3b6f7 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyStates.java @@ -0,0 +1,181 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import rx.Observable; + +/** + * Type representing PolicyStates. + */ +public interface PolicyStates { + /** + * Queries policy states for the resources under the management group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForManagementGroupAsync(PolicyStatesResource policyStatesResource, String managementGroupName); + + /** + * Summarizes policy states for the resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable summarizeForManagementGroupAsync(String managementGroupName); + + /** + * Queries policy states for the resources under the subscription. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForSubscriptionAsync(PolicyStatesResource policyStatesResource, String subscriptionId); + + /** + * Summarizes policy states for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable summarizeForSubscriptionAsync(String subscriptionId); + + /** + * Queries policy states for the resources under the resource group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForResourceGroupAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName); + + /** + * Summarizes policy states for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable summarizeForResourceGroupAsync(String subscriptionId, String resourceGroupName); + + /** + * Queries policy states for the resource. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForResourceAsync(PolicyStatesResource policyStatesResource, String resourceId); + + /** + * Summarizes policy states for the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable summarizeForResourceAsync(String resourceId); + + /** + * Queries policy states for the subscription level policy set definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForPolicySetDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName); + + /** + * Summarizes policy states for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable summarizeForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName); + + /** + * Queries policy states for the subscription level policy definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForPolicyDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName); + + /** + * Summarizes policy states for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable summarizeForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName); + + /** + * Queries policy states for the subscription level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName); + + /** + * Summarizes policy states for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable summarizeForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName); + + /** + * Queries policy states for the resource group level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName); + + /** + * Summarizes policy states for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable summarizeForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyStatesQueryResults.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyStatesQueryResults.java new file mode 100644 index 0000000000000..bc17e2bd81ec8 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyStatesQueryResults.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyInsightsManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyStatesQueryResultsInner; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyStateInner; +import java.util.List; + +/** + * Type representing PolicyStatesQueryResults. + */ +public interface PolicyStatesQueryResults extends HasInner, HasManager { + /** + * @return the odatacontext value. + */ + String odatacontext(); + + /** + * @return the odatacount value. + */ + Integer odatacount(); + + /** + * @return the value value. + */ + List value(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyStatesResource.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyStatesResource.java new file mode 100644 index 0000000000000..3e972544f7fa9 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyStatesResource.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for PolicyStatesResource. + */ +public final class PolicyStatesResource extends ExpandableStringEnum { + /** Static value default for PolicyStatesResource. */ + public static final PolicyStatesResource DEFAULT = fromString("default"); + + /** Static value latest for PolicyStatesResource. */ + public static final PolicyStatesResource LATEST = fromString("latest"); + + /** + * Creates or finds a PolicyStatesResource from its string representation. + * @param name a name to look for + * @return the corresponding PolicyStatesResource + */ + @JsonCreator + public static PolicyStatesResource fromString(String name) { + return fromString(name, PolicyStatesResource.class); + } + + /** + * @return known PolicyStatesResource values + */ + public static Collection values() { + return values(PolicyStatesResource.class); + } +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyTrackedResource.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyTrackedResource.java new file mode 100644 index 0000000000000..f63a362a8ea7a --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyTrackedResource.java @@ -0,0 +1,46 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyInsightsManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyTrackedResourceInner; +import org.joda.time.DateTime; + +/** + * Type representing PolicyTrackedResource. + */ +public interface PolicyTrackedResource extends HasInner, HasManager { + /** + * @return the createdBy value. + */ + TrackedResourceModificationDetails createdBy(); + + /** + * @return the lastModifiedBy value. + */ + TrackedResourceModificationDetails lastModifiedBy(); + + /** + * @return the lastUpdateUtc value. + */ + DateTime lastUpdateUtc(); + + /** + * @return the policyDetails value. + */ + PolicyDetails policyDetails(); + + /** + * @return the trackedResourceId value. + */ + String trackedResourceId(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyTrackedResources.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyTrackedResources.java new file mode 100644 index 0000000000000..4b5cccee73c1c --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/PolicyTrackedResources.java @@ -0,0 +1,54 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import rx.Observable; + +/** + * Type representing PolicyTrackedResources. + */ +public interface PolicyTrackedResources { + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForManagementGroupAsync(final String managementGroupName); + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForSubscriptionAsync(final String subscriptionId); + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForResourceGroupAsync(final String resourceGroupName, final String subscriptionId); + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listQueryResultsForResourceAsync(final String resourceId); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryFailure.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryFailure.java new file mode 100644 index 0000000000000..4dd1b8c1dc6fd --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryFailure.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Error response. + */ +public class QueryFailure { + /** + * Error definition. + */ + @JsonProperty(value = "error") + private QueryFailureError error; + + /** + * Get error definition. + * + * @return the error value + */ + public QueryFailureError error() { + return this.error; + } + + /** + * Set error definition. + * + * @param error the error value to set + * @return the QueryFailure object itself. + */ + public QueryFailure withError(QueryFailureError error) { + this.error = error; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryFailureError.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryFailureError.java new file mode 100644 index 0000000000000..7f88b7e6d8744 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryFailureError.java @@ -0,0 +1,48 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Error definition. + */ +public class QueryFailureError { + /** + * Service specific error code which serves as the substatus for the HTTP + * error code. + */ + @JsonProperty(value = "code", access = JsonProperty.Access.WRITE_ONLY) + private String code; + + /** + * Description of the error. + */ + @JsonProperty(value = "message", access = JsonProperty.Access.WRITE_ONLY) + private String message; + + /** + * Get service specific error code which serves as the substatus for the HTTP error code. + * + * @return the code value + */ + public String code() { + return this.code; + } + + /** + * Get description of the error. + * + * @return the message value + */ + public String message() { + return this.message; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryFailureException.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryFailureException.java new file mode 100644 index 0000000000000..3fdbfac7d4bc7 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryFailureException.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.rest.RestException; +import okhttp3.ResponseBody; +import retrofit2.Response; + +/** + * Exception thrown for an invalid response with QueryFailure information. + */ +public class QueryFailureException extends RestException { + /** + * Initializes a new instance of the QueryFailureException class. + * + * @param message the exception message or the response content if a message is not available + * @param response the HTTP response + */ + public QueryFailureException(final String message, final Response response) { + super(message, response); + } + + /** + * Initializes a new instance of the QueryFailureException class. + * + * @param message the exception message or the response content if a message is not available + * @param response the HTTP response + * @param body the deserialized response body + */ + public QueryFailureException(final String message, final Response response, final QueryFailure body) { + super(message, response, body); + } + + @Override + public QueryFailure body() { + return (QueryFailure) super.body(); + } +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryOptions.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryOptions.java new file mode 100644 index 0000000000000..5289127854c76 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/QueryOptions.java @@ -0,0 +1,233 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Additional parameters for a set of operations. + */ +public class QueryOptions { + /** + * Maximum number of records to return. + */ + @JsonProperty(value = "") + private Integer top; + + /** + * OData filter expression. + */ + @JsonProperty(value = "") + private String filter; + + /** + * Ordering expression using OData notation. One or more comma-separated + * column names with an optional "desc" (the default) or "asc", e.g. + * "$orderby=PolicyAssignmentId, ResourceId asc". + */ + @JsonProperty(value = "") + private String orderBy; + + /** + * Select expression using OData notation. Limits the columns on each + * record to just those requested, e.g. "$select=PolicyAssignmentId, + * ResourceId". + */ + @JsonProperty(value = "") + private String select; + + /** + * ISO 8601 formatted timestamp specifying the start time of the interval + * to query. When not specified, the service uses ($to - 1-day). + */ + @JsonProperty(value = "") + private DateTime from; + + /** + * ISO 8601 formatted timestamp specifying the end time of the interval to + * query. When not specified, the service uses request time. + */ + @JsonProperty(value = "") + private DateTime to; + + /** + * OData apply expression for aggregations. + */ + @JsonProperty(value = "") + private String apply; + + /** + * The $expand query parameter. For example, to expand + * policyEvaluationDetails, use $expand=policyEvaluationDetails. + */ + @JsonProperty(value = "") + private String expand; + + /** + * Get maximum number of records to return. + * + * @return the top value + */ + public Integer top() { + return this.top; + } + + /** + * Set maximum number of records to return. + * + * @param top the top value to set + * @return the QueryOptions object itself. + */ + public QueryOptions withTop(Integer top) { + this.top = top; + return this; + } + + /** + * Get oData filter expression. + * + * @return the filter value + */ + public String filter() { + return this.filter; + } + + /** + * Set oData filter expression. + * + * @param filter the filter value to set + * @return the QueryOptions object itself. + */ + public QueryOptions withFilter(String filter) { + this.filter = filter; + return this; + } + + /** + * Get ordering expression using OData notation. One or more comma-separated column names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". + * + * @return the orderBy value + */ + public String orderBy() { + return this.orderBy; + } + + /** + * Set ordering expression using OData notation. One or more comma-separated column names with an optional "desc" (the default) or "asc", e.g. "$orderby=PolicyAssignmentId, ResourceId asc". + * + * @param orderBy the orderBy value to set + * @return the QueryOptions object itself. + */ + public QueryOptions withOrderBy(String orderBy) { + this.orderBy = orderBy; + return this; + } + + /** + * Get select expression using OData notation. Limits the columns on each record to just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". + * + * @return the select value + */ + public String select() { + return this.select; + } + + /** + * Set select expression using OData notation. Limits the columns on each record to just those requested, e.g. "$select=PolicyAssignmentId, ResourceId". + * + * @param select the select value to set + * @return the QueryOptions object itself. + */ + public QueryOptions withSelect(String select) { + this.select = select; + return this; + } + + /** + * Get iSO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, the service uses ($to - 1-day). + * + * @return the from value + */ + public DateTime from() { + return this.from; + } + + /** + * Set iSO 8601 formatted timestamp specifying the start time of the interval to query. When not specified, the service uses ($to - 1-day). + * + * @param from the from value to set + * @return the QueryOptions object itself. + */ + public QueryOptions withFrom(DateTime from) { + this.from = from; + return this; + } + + /** + * Get iSO 8601 formatted timestamp specifying the end time of the interval to query. When not specified, the service uses request time. + * + * @return the to value + */ + public DateTime to() { + return this.to; + } + + /** + * Set iSO 8601 formatted timestamp specifying the end time of the interval to query. When not specified, the service uses request time. + * + * @param to the to value to set + * @return the QueryOptions object itself. + */ + public QueryOptions withTo(DateTime to) { + this.to = to; + return this; + } + + /** + * Get oData apply expression for aggregations. + * + * @return the apply value + */ + public String apply() { + return this.apply; + } + + /** + * Set oData apply expression for aggregations. + * + * @param apply the apply value to set + * @return the QueryOptions object itself. + */ + public QueryOptions withApply(String apply) { + this.apply = apply; + return this; + } + + /** + * Get the $expand query parameter. For example, to expand policyEvaluationDetails, use $expand=policyEvaluationDetails. + * + * @return the expand value + */ + public String expand() { + return this.expand; + } + + /** + * Set the $expand query parameter. For example, to expand policyEvaluationDetails, use $expand=policyEvaluationDetails. + * + * @param expand the expand value to set + * @return the QueryOptions object itself. + */ + public QueryOptions withExpand(String expand) { + this.expand = expand; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Remediation.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Remediation.java new file mode 100644 index 0000000000000..2cb39df9700fa --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Remediation.java @@ -0,0 +1,223 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.RemediationInner; +import com.microsoft.azure.arm.model.Indexable; +import com.microsoft.azure.arm.model.Updatable; +import com.microsoft.azure.arm.model.Appliable; +import com.microsoft.azure.arm.model.Creatable; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyInsightsManager; +import org.joda.time.DateTime; + +/** + * Type representing Remediation. + */ +public interface Remediation extends HasInner, Indexable, Updatable, HasManager { + /** + * @return the createdOn value. + */ + DateTime createdOn(); + + /** + * @return the deploymentStatus value. + */ + RemediationDeploymentSummary deploymentStatus(); + + /** + * @return the filters value. + */ + RemediationFilters filters(); + + /** + * @return the id value. + */ + String id(); + + /** + * @return the lastUpdatedOn value. + */ + DateTime lastUpdatedOn(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the policyAssignmentId value. + */ + String policyAssignmentId(); + + /** + * @return the policyDefinitionReferenceId value. + */ + String policyDefinitionReferenceId(); + + /** + * @return the provisioningState value. + */ + String provisioningState(); + + /** + * @return the resourceDiscoveryMode value. + */ + ResourceDiscoveryMode resourceDiscoveryMode(); + + /** + * @return the type value. + */ + String type(); + + /** + * The entirety of the Remediation definition. + */ + interface Definition extends DefinitionStages.Blank, DefinitionStages.WithManagementGroupId, DefinitionStages.WithCreate { + } + + /** + * Grouping of Remediation definition stages. + */ + interface DefinitionStages { + /** + * The first stage of a Remediation definition. + */ + interface Blank extends WithManagementGroupId { + } + + /** + * The stage of the remediation definition allowing to specify ManagementGroupId. + */ + interface WithManagementGroupId { + /** + * Specifies managementGroupId. + * @param managementGroupId Management group ID + * @return the next definition stage + */ + WithCreate withExistingManagementGroupId(String managementGroupId); + } + + /** + * The stage of the remediation definition allowing to specify Filters. + */ + interface WithFilters { + /** + * Specifies filters. + * @param filters The filters that will be applied to determine which resources to remediate + * @return the next definition stage + */ + WithCreate withFilters(RemediationFilters filters); + } + + /** + * The stage of the remediation definition allowing to specify PolicyAssignmentId. + */ + interface WithPolicyAssignmentId { + /** + * Specifies policyAssignmentId. + * @param policyAssignmentId The resource ID of the policy assignment that should be remediated + * @return the next definition stage + */ + WithCreate withPolicyAssignmentId(String policyAssignmentId); + } + + /** + * The stage of the remediation definition allowing to specify PolicyDefinitionReferenceId. + */ + interface WithPolicyDefinitionReferenceId { + /** + * Specifies policyDefinitionReferenceId. + * @param policyDefinitionReferenceId The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition + * @return the next definition stage + */ + WithCreate withPolicyDefinitionReferenceId(String policyDefinitionReferenceId); + } + + /** + * The stage of the remediation definition allowing to specify ResourceDiscoveryMode. + */ + interface WithResourceDiscoveryMode { + /** + * Specifies resourceDiscoveryMode. + * @param resourceDiscoveryMode The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. Possible values include: 'ExistingNonCompliant', 'ReEvaluateCompliance' + * @return the next definition stage + */ + WithCreate withResourceDiscoveryMode(ResourceDiscoveryMode resourceDiscoveryMode); + } + + /** + * The stage of the definition which contains all the minimum required inputs for + * the resource to be created (via {@link WithCreate#create()}), but also allows + * for any other optional settings to be specified. + */ + interface WithCreate extends Creatable, DefinitionStages.WithFilters, DefinitionStages.WithPolicyAssignmentId, DefinitionStages.WithPolicyDefinitionReferenceId, DefinitionStages.WithResourceDiscoveryMode { + } + } + /** + * The template for a Remediation update operation, containing all the settings that can be modified. + */ + interface Update extends Appliable, UpdateStages.WithFilters, UpdateStages.WithPolicyAssignmentId, UpdateStages.WithPolicyDefinitionReferenceId, UpdateStages.WithResourceDiscoveryMode { + } + + /** + * Grouping of Remediation update stages. + */ + interface UpdateStages { + /** + * The stage of the remediation update allowing to specify Filters. + */ + interface WithFilters { + /** + * Specifies filters. + * @param filters The filters that will be applied to determine which resources to remediate + * @return the next update stage + */ + Update withFilters(RemediationFilters filters); + } + + /** + * The stage of the remediation update allowing to specify PolicyAssignmentId. + */ + interface WithPolicyAssignmentId { + /** + * Specifies policyAssignmentId. + * @param policyAssignmentId The resource ID of the policy assignment that should be remediated + * @return the next update stage + */ + Update withPolicyAssignmentId(String policyAssignmentId); + } + + /** + * The stage of the remediation update allowing to specify PolicyDefinitionReferenceId. + */ + interface WithPolicyDefinitionReferenceId { + /** + * Specifies policyDefinitionReferenceId. + * @param policyDefinitionReferenceId The policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition + * @return the next update stage + */ + Update withPolicyDefinitionReferenceId(String policyDefinitionReferenceId); + } + + /** + * The stage of the remediation update allowing to specify ResourceDiscoveryMode. + */ + interface WithResourceDiscoveryMode { + /** + * Specifies resourceDiscoveryMode. + * @param resourceDiscoveryMode The way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. Possible values include: 'ExistingNonCompliant', 'ReEvaluateCompliance' + * @return the next update stage + */ + Update withResourceDiscoveryMode(ResourceDiscoveryMode resourceDiscoveryMode); + } + + } +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/RemediationDeployment.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/RemediationDeployment.java new file mode 100644 index 0000000000000..d1da37ba1b61d --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/RemediationDeployment.java @@ -0,0 +1,56 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyInsightsManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.RemediationDeploymentInner; +import org.joda.time.DateTime; + +/** + * Type representing RemediationDeployment. + */ +public interface RemediationDeployment extends HasInner, HasManager { + /** + * @return the createdOn value. + */ + DateTime createdOn(); + + /** + * @return the deploymentId value. + */ + String deploymentId(); + + /** + * @return the error value. + */ + ErrorDefinition error(); + + /** + * @return the lastUpdatedOn value. + */ + DateTime lastUpdatedOn(); + + /** + * @return the remediatedResourceId value. + */ + String remediatedResourceId(); + + /** + * @return the resourceLocation value. + */ + String resourceLocation(); + + /** + * @return the status value. + */ + String status(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/RemediationDeploymentSummary.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/RemediationDeploymentSummary.java new file mode 100644 index 0000000000000..97995be9004ed --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/RemediationDeploymentSummary.java @@ -0,0 +1,64 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The deployment status summary for all deployments created by the + * remediation. + */ +public class RemediationDeploymentSummary { + /** + * The number of deployments required by the remediation. + */ + @JsonProperty(value = "totalDeployments", access = JsonProperty.Access.WRITE_ONLY) + private Integer totalDeployments; + + /** + * The number of deployments required by the remediation that have + * succeeded. + */ + @JsonProperty(value = "successfulDeployments", access = JsonProperty.Access.WRITE_ONLY) + private Integer successfulDeployments; + + /** + * The number of deployments required by the remediation that have failed. + */ + @JsonProperty(value = "failedDeployments", access = JsonProperty.Access.WRITE_ONLY) + private Integer failedDeployments; + + /** + * Get the number of deployments required by the remediation. + * + * @return the totalDeployments value + */ + public Integer totalDeployments() { + return this.totalDeployments; + } + + /** + * Get the number of deployments required by the remediation that have succeeded. + * + * @return the successfulDeployments value + */ + public Integer successfulDeployments() { + return this.successfulDeployments; + } + + /** + * Get the number of deployments required by the remediation that have failed. + * + * @return the failedDeployments value + */ + public Integer failedDeployments() { + return this.failedDeployments; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/RemediationFilters.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/RemediationFilters.java new file mode 100644 index 0000000000000..08b8c19a528c2 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/RemediationFilters.java @@ -0,0 +1,44 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The filters that will be applied to determine which resources to remediate. + */ +public class RemediationFilters { + /** + * The resource locations that will be remediated. + */ + @JsonProperty(value = "locations") + private List locations; + + /** + * Get the resource locations that will be remediated. + * + * @return the locations value + */ + public List locations() { + return this.locations; + } + + /** + * Set the resource locations that will be remediated. + * + * @param locations the locations value to set + * @return the RemediationFilters object itself. + */ + public RemediationFilters withLocations(List locations) { + this.locations = locations; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Remediations.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Remediations.java new file mode 100644 index 0000000000000..4455a2c0855f1 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Remediations.java @@ -0,0 +1,257 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.collection.SupportsCreating; +import rx.Completable; +import rx.Observable; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.RemediationInner; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.RemediationsInner; +import com.microsoft.azure.arm.model.HasInner; + +/** + * Type representing Remediations. + */ +public interface Remediations extends SupportsCreating, HasInner { + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listDeploymentsAtManagementGroupAsync(final String managementGroupId, final String remediationName); + + /** + * Cancels a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable cancelAtManagementGroupAsync(String managementGroupId, String remediationName); + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listForManagementGroupAsync(final String managementGroupId); + + /** + * Gets an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAtManagementGroupAsync(String managementGroupId, String remediationName); + + /** + * Deletes an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable deleteAtManagementGroupAsync(String managementGroupId, String remediationName); + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listDeploymentsAtSubscriptionAsync(final String subscriptionId, final String remediationName); + + /** + * Cancels a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable cancelAtSubscriptionAsync(String subscriptionId, String remediationName); + + /** + * Creates or updates a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable createOrUpdateAtSubscriptionAsync(String subscriptionId, String remediationName, RemediationInner parameters); + + /** + * Gets an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAtSubscriptionAsync(String subscriptionId, String remediationName); + + /** + * Deletes an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable deleteAtSubscriptionAsync(String subscriptionId, String remediationName); + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listDeploymentsAtResourceGroupAsync(final String subscriptionId, final String resourceGroupName, final String remediationName); + + /** + * Cancels a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable cancelAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName); + + /** + * Creates or updates a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable createOrUpdateAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName, RemediationInner parameters); + + /** + * Gets an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getByResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName); + + /** + * Deletes an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable deleteAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName); + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listDeploymentsAtResourceAsync(final String resourceId, final String remediationName); + + /** + * Cancel a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable cancelAtResourceAsync(String resourceId, String remediationName); + + /** + * Creates or updates a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable createOrUpdateAtResourceAsync(String resourceId, String remediationName, RemediationInner parameters); + + /** + * Gets an existing remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable getAtResourceAsync(String resourceId, String remediationName); + + /** + * Deletes an existing remediation at individual resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable deleteAtResourceAsync(String resourceId, String remediationName); + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listAsync(final String subscriptionId); + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listByResourceGroupAsync(final String subscriptionId, final String resourceGroupName); + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable for the request + */ + Observable listForResourceAsync(final String resourceId); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ResourceDiscoveryMode.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ResourceDiscoveryMode.java new file mode 100644 index 0000000000000..0b7002b83273e --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/ResourceDiscoveryMode.java @@ -0,0 +1,41 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import java.util.Collection; +import com.fasterxml.jackson.annotation.JsonCreator; +import com.microsoft.rest.ExpandableStringEnum; + +/** + * Defines values for ResourceDiscoveryMode. + */ +public final class ResourceDiscoveryMode extends ExpandableStringEnum { + /** Static value ExistingNonCompliant for ResourceDiscoveryMode. */ + public static final ResourceDiscoveryMode EXISTING_NON_COMPLIANT = fromString("ExistingNonCompliant"); + + /** Static value ReEvaluateCompliance for ResourceDiscoveryMode. */ + public static final ResourceDiscoveryMode RE_EVALUATE_COMPLIANCE = fromString("ReEvaluateCompliance"); + + /** + * Creates or finds a ResourceDiscoveryMode from its string representation. + * @param name a name to look for + * @return the corresponding ResourceDiscoveryMode + */ + @JsonCreator + public static ResourceDiscoveryMode fromString(String name) { + return fromString(name, ResourceDiscoveryMode.class); + } + + /** + * @return known ResourceDiscoveryMode values + */ + public static Collection values() { + return values(ResourceDiscoveryMode.class); + } +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/SlimPolicyMetadata.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/SlimPolicyMetadata.java new file mode 100644 index 0000000000000..d9f43c417ceda --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/SlimPolicyMetadata.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyInsightsManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.SlimPolicyMetadataInner; + +/** + * Type representing SlimPolicyMetadata. + */ +public interface SlimPolicyMetadata extends HasInner, HasManager { + /** + * @return the additionalContentUrl value. + */ + String additionalContentUrl(); + + /** + * @return the category value. + */ + String category(); + + /** + * @return the id value. + */ + String id(); + + /** + * @return the metadata value. + */ + Object metadata(); + + /** + * @return the metadataId value. + */ + String metadataId(); + + /** + * @return the name value. + */ + String name(); + + /** + * @return the owner value. + */ + String owner(); + + /** + * @return the title value. + */ + String title(); + + /** + * @return the type value. + */ + String type(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/SummarizeResults.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/SummarizeResults.java new file mode 100644 index 0000000000000..e21699220c9ca --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/SummarizeResults.java @@ -0,0 +1,36 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.microsoft.azure.arm.model.HasInner; +import com.microsoft.azure.arm.resources.models.HasManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.PolicyInsightsManager; +import com.microsoft.azure.management.policyinsights.v2019_10_01.implementation.SummarizeResultsInner; +import java.util.List; + +/** + * Type representing SummarizeResults. + */ +public interface SummarizeResults extends HasInner, HasManager { + /** + * @return the odatacontext value. + */ + String odatacontext(); + + /** + * @return the odatacount value. + */ + Integer odatacount(); + + /** + * @return the value value. + */ + List value(); + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Summary.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Summary.java new file mode 100644 index 0000000000000..acd680ac56954 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/Summary.java @@ -0,0 +1,124 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Summary results. + */ +public class Summary { + /** + * OData entity ID; always set to null since summaries do not have an + * entity ID. + */ + @JsonProperty(value = "@odata\\.id") + private String odataid; + + /** + * OData context string; used by OData clients to resolve type information + * based on metadata. + */ + @JsonProperty(value = "@odata\\.context") + private String odatacontext; + + /** + * Compliance summary for all policy assignments. + */ + @JsonProperty(value = "results") + private SummaryResults results; + + /** + * Policy assignments summary. + */ + @JsonProperty(value = "policyAssignments") + private List policyAssignments; + + /** + * Get oData entity ID; always set to null since summaries do not have an entity ID. + * + * @return the odataid value + */ + public String odataid() { + return this.odataid; + } + + /** + * Set oData entity ID; always set to null since summaries do not have an entity ID. + * + * @param odataid the odataid value to set + * @return the Summary object itself. + */ + public Summary withOdataid(String odataid) { + this.odataid = odataid; + return this; + } + + /** + * Get oData context string; used by OData clients to resolve type information based on metadata. + * + * @return the odatacontext value + */ + public String odatacontext() { + return this.odatacontext; + } + + /** + * Set oData context string; used by OData clients to resolve type information based on metadata. + * + * @param odatacontext the odatacontext value to set + * @return the Summary object itself. + */ + public Summary withOdatacontext(String odatacontext) { + this.odatacontext = odatacontext; + return this; + } + + /** + * Get compliance summary for all policy assignments. + * + * @return the results value + */ + public SummaryResults results() { + return this.results; + } + + /** + * Set compliance summary for all policy assignments. + * + * @param results the results value to set + * @return the Summary object itself. + */ + public Summary withResults(SummaryResults results) { + this.results = results; + return this; + } + + /** + * Get policy assignments summary. + * + * @return the policyAssignments value + */ + public List policyAssignments() { + return this.policyAssignments; + } + + /** + * Set policy assignments summary. + * + * @param policyAssignments the policyAssignments value to set + * @return the Summary object itself. + */ + public Summary withPolicyAssignments(List policyAssignments) { + this.policyAssignments = policyAssignments; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/SummaryResults.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/SummaryResults.java new file mode 100644 index 0000000000000..053f0d7fc87f6 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/SummaryResults.java @@ -0,0 +1,179 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Compliance summary on a particular summary level. + */ +public class SummaryResults { + /** + * HTTP POST URI for queryResults action on Microsoft.PolicyInsights to + * retrieve raw results for the compliance summary. This property will not + * be available by default in future API versions, but could be queried + * explicitly. + */ + @JsonProperty(value = "queryResultsUri") + private String queryResultsUri; + + /** + * Number of non-compliant resources. + */ + @JsonProperty(value = "nonCompliantResources") + private Integer nonCompliantResources; + + /** + * Number of non-compliant policies. + */ + @JsonProperty(value = "nonCompliantPolicies") + private Integer nonCompliantPolicies; + + /** + * The resources summary at this level. + */ + @JsonProperty(value = "resourceDetails") + private List resourceDetails; + + /** + * The policy artifact summary at this level. For query scope level, it + * represents policy assignment summary. For policy assignment level, it + * represents policy definitions summary. + */ + @JsonProperty(value = "policyDetails") + private List policyDetails; + + /** + * The policy definition group summary at this level. + */ + @JsonProperty(value = "policyGroupDetails") + private List policyGroupDetails; + + /** + * Get hTTP POST URI for queryResults action on Microsoft.PolicyInsights to retrieve raw results for the compliance summary. This property will not be available by default in future API versions, but could be queried explicitly. + * + * @return the queryResultsUri value + */ + public String queryResultsUri() { + return this.queryResultsUri; + } + + /** + * Set hTTP POST URI for queryResults action on Microsoft.PolicyInsights to retrieve raw results for the compliance summary. This property will not be available by default in future API versions, but could be queried explicitly. + * + * @param queryResultsUri the queryResultsUri value to set + * @return the SummaryResults object itself. + */ + public SummaryResults withQueryResultsUri(String queryResultsUri) { + this.queryResultsUri = queryResultsUri; + return this; + } + + /** + * Get number of non-compliant resources. + * + * @return the nonCompliantResources value + */ + public Integer nonCompliantResources() { + return this.nonCompliantResources; + } + + /** + * Set number of non-compliant resources. + * + * @param nonCompliantResources the nonCompliantResources value to set + * @return the SummaryResults object itself. + */ + public SummaryResults withNonCompliantResources(Integer nonCompliantResources) { + this.nonCompliantResources = nonCompliantResources; + return this; + } + + /** + * Get number of non-compliant policies. + * + * @return the nonCompliantPolicies value + */ + public Integer nonCompliantPolicies() { + return this.nonCompliantPolicies; + } + + /** + * Set number of non-compliant policies. + * + * @param nonCompliantPolicies the nonCompliantPolicies value to set + * @return the SummaryResults object itself. + */ + public SummaryResults withNonCompliantPolicies(Integer nonCompliantPolicies) { + this.nonCompliantPolicies = nonCompliantPolicies; + return this; + } + + /** + * Get the resources summary at this level. + * + * @return the resourceDetails value + */ + public List resourceDetails() { + return this.resourceDetails; + } + + /** + * Set the resources summary at this level. + * + * @param resourceDetails the resourceDetails value to set + * @return the SummaryResults object itself. + */ + public SummaryResults withResourceDetails(List resourceDetails) { + this.resourceDetails = resourceDetails; + return this; + } + + /** + * Get the policy artifact summary at this level. For query scope level, it represents policy assignment summary. For policy assignment level, it represents policy definitions summary. + * + * @return the policyDetails value + */ + public List policyDetails() { + return this.policyDetails; + } + + /** + * Set the policy artifact summary at this level. For query scope level, it represents policy assignment summary. For policy assignment level, it represents policy definitions summary. + * + * @param policyDetails the policyDetails value to set + * @return the SummaryResults object itself. + */ + public SummaryResults withPolicyDetails(List policyDetails) { + this.policyDetails = policyDetails; + return this; + } + + /** + * Get the policy definition group summary at this level. + * + * @return the policyGroupDetails value + */ + public List policyGroupDetails() { + return this.policyGroupDetails; + } + + /** + * Set the policy definition group summary at this level. + * + * @param policyGroupDetails the policyGroupDetails value to set + * @return the SummaryResults object itself. + */ + public SummaryResults withPolicyGroupDetails(List policyGroupDetails) { + this.policyGroupDetails = policyGroupDetails; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/TrackedResourceModificationDetails.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/TrackedResourceModificationDetails.java new file mode 100644 index 0000000000000..682d717217370 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/TrackedResourceModificationDetails.java @@ -0,0 +1,65 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * The details of the policy triggered deployment that created or modified the + * tracked resource. + */ +public class TrackedResourceModificationDetails { + /** + * The details of the policy that created or modified the tracked resource. + */ + @JsonProperty(value = "policyDetails", access = JsonProperty.Access.WRITE_ONLY) + private PolicyDetails policyDetails; + + /** + * The ID of the deployment that created or modified the tracked resource. + */ + @JsonProperty(value = "deploymentId", access = JsonProperty.Access.WRITE_ONLY) + private String deploymentId; + + /** + * Timestamp of the deployment that created or modified the tracked + * resource. + */ + @JsonProperty(value = "deploymentTime", access = JsonProperty.Access.WRITE_ONLY) + private DateTime deploymentTime; + + /** + * Get the details of the policy that created or modified the tracked resource. + * + * @return the policyDetails value + */ + public PolicyDetails policyDetails() { + return this.policyDetails; + } + + /** + * Get the ID of the deployment that created or modified the tracked resource. + * + * @return the deploymentId value + */ + public String deploymentId() { + return this.deploymentId; + } + + /** + * Get timestamp of the deployment that created or modified the tracked resource. + * + * @return the deploymentTime value + */ + public DateTime deploymentTime() { + return this.deploymentTime; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/TypedErrorInfo.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/TypedErrorInfo.java new file mode 100644 index 0000000000000..69f42bf6cca86 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/TypedErrorInfo.java @@ -0,0 +1,47 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01; + +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Scenario specific error details. + */ +public class TypedErrorInfo { + /** + * The type of included error details. + */ + @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY) + private String type; + + /** + * The scenario specific error details. + */ + @JsonProperty(value = "info", access = JsonProperty.Access.WRITE_ONLY) + private Object info; + + /** + * Get the type of included error details. + * + * @return the type value + */ + public String type() { + return this.type; + } + + /** + * Get the scenario specific error details. + * + * @return the info value + */ + public Object info() { + return this.info; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/IdParsingUtils.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/IdParsingUtils.java new file mode 100644 index 0000000000000..7efbf0dcb41fd --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/IdParsingUtils.java @@ -0,0 +1,57 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; +import java.util.Arrays; +import java.util.Iterator; + +class IdParsingUtils { + public static String getValueFromIdByName(String id, String name) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (part.equalsIgnoreCase(name)) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + } + return null; + } + + public static String getValueFromIdByPosition(String id, int pos) { + if (id == null) { + return null; + } + Iterable iterable = Arrays.asList(id.split("/")); + Iterator itr = iterable.iterator(); + int index = 0; + while (itr.hasNext()) { + String part = itr.next(); + if (part != null && part.trim() != "") { + if (index == pos) { + if (itr.hasNext()) { + return itr.next(); + } else { + return null; + } + } + } + index++; + } + return null; + } +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationInner.java new file mode 100644 index 0000000000000..f82211786fcea --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationInner.java @@ -0,0 +1,70 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.OperationDisplay; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Operation definition. + */ +public class OperationInner { + /** + * Operation name. + */ + @JsonProperty(value = "name") + private String name; + + /** + * Display metadata associated with the operation. + */ + @JsonProperty(value = "display") + private OperationDisplay display; + + /** + * Get operation name. + * + * @return the name value + */ + public String name() { + return this.name; + } + + /** + * Set operation name. + * + * @param name the name value to set + * @return the OperationInner object itself. + */ + public OperationInner withName(String name) { + this.name = name; + return this; + } + + /** + * Get display metadata associated with the operation. + * + * @return the display value + */ + public OperationDisplay display() { + return this.display; + } + + /** + * Set display metadata associated with the operation. + * + * @param display the display value to set + * @return the OperationInner object itself. + */ + public OperationInner withDisplay(OperationDisplay display) { + this.display = display; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsImpl.java new file mode 100644 index 0000000000000..a24bf8fcd54c4 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsImpl.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.policyinsights.v2019_10_01.Operations; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.management.policyinsights.v2019_10_01.OperationsListResults; + +class OperationsImpl extends WrapperImpl implements Operations { + private final PolicyInsightsManager manager; + + OperationsImpl(PolicyInsightsManager manager) { + super(manager.inner().operations()); + this.manager = manager; + } + + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public Observable listAsync() { + OperationsInner client = this.inner(); + return client.listAsync() + .map(new Func1() { + @Override + public OperationsListResults call(OperationsListResultsInner inner) { + return new OperationsListResultsImpl(inner, manager()); + } + }); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsInner.java new file mode 100644 index 0000000000000..413ac9db8a7e1 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsInner.java @@ -0,0 +1,126 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.management.policyinsights.v2019_10_01.QueryFailureException; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import java.io.IOException; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Operations. + */ +public class OperationsInner { + /** The Retrofit service to perform REST calls. */ + private OperationsService service; + /** The service client containing this operation class. */ + private PolicyInsightsClientImpl client; + + /** + * Initializes an instance of OperationsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public OperationsInner(Retrofit retrofit, PolicyInsightsClientImpl client) { + this.service = retrofit.create(OperationsService.class); + this.client = client; + } + + /** + * The interface defining all the services for Operations to be + * used by Retrofit to perform actually REST calls. + */ + interface OperationsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Operations list" }) + @GET("providers/Microsoft.PolicyInsights/operations") + Observable> list(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Lists available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the OperationsListResultsInner object if successful. + */ + public OperationsListResultsInner list() { + return listWithServiceResponseAsync().toBlocking().single().body(); + } + + /** + * Lists available operations. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listAsync(final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listWithServiceResponseAsync(), serviceCallback); + } + + /** + * Lists available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the OperationsListResultsInner object + */ + public Observable listAsync() { + return listWithServiceResponseAsync().map(new Func1, OperationsListResultsInner>() { + @Override + public OperationsListResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Lists available operations. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the OperationsListResultsInner object + */ + public Observable> listWithServiceResponseAsync() { + final String apiVersion = "2019-10-01"; + return service.list(apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listDelegate(Response response) throws QueryFailureException, IOException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsListResultsImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsListResultsImpl.java new file mode 100644 index 0000000000000..9c887539a1fcb --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsListResultsImpl.java @@ -0,0 +1,37 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.OperationsListResults; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import java.util.List; + +class OperationsListResultsImpl extends WrapperImpl implements OperationsListResults { + private final PolicyInsightsManager manager; + OperationsListResultsImpl(OperationsListResultsInner inner, PolicyInsightsManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public Integer odatacount() { + return this.inner().odatacount(); + } + + @Override + public List value() { + return this.inner().value(); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsListResultsInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsListResultsInner.java new file mode 100644 index 0000000000000..7ed9cdbb55f8a --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/OperationsListResultsInner.java @@ -0,0 +1,70 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * List of available operations. + */ +public class OperationsListResultsInner { + /** + * OData entity count; represents the number of operations returned. + */ + @JsonProperty(value = "@odata\\.count") + private Integer odatacount; + + /** + * List of available operations. + */ + @JsonProperty(value = "value") + private List value; + + /** + * Get oData entity count; represents the number of operations returned. + * + * @return the odatacount value + */ + public Integer odatacount() { + return this.odatacount; + } + + /** + * Set oData entity count; represents the number of operations returned. + * + * @param odatacount the odatacount value to set + * @return the OperationsListResultsInner object itself. + */ + public OperationsListResultsInner withOdatacount(Integer odatacount) { + this.odatacount = odatacount; + return this; + } + + /** + * Get list of available operations. + * + * @return the value value + */ + public List value() { + return this.value; + } + + /** + * Set list of available operations. + * + * @param value the value value to set + * @return the OperationsListResultsInner object itself. + */ + public OperationsListResultsInner withValue(List value) { + this.value = value; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PageImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PageImpl.java new file mode 100644 index 0000000000000..708d9aa902681 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PageImpl.java @@ -0,0 +1,75 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.azure.Page; +import java.util.List; + +/** + * An instance of this class defines a page of Azure resources and a link to + * get the next page of resources, if any. + * + * @param type of Azure resource + */ +public class PageImpl implements Page { + /** + * The link to the next page. + */ + @JsonProperty("nextLink") + private String nextPageLink; + + /** + * The list of items. + */ + @JsonProperty("value") + private List items; + + /** + * Gets the link to the next page. + * + * @return the link to the next page. + */ + @Override + public String nextPageLink() { + return this.nextPageLink; + } + + /** + * Gets the list of items. + * + * @return the list of items in {@link List}. + */ + @Override + public List items() { + return items; + } + + /** + * Sets the link to the next page. + * + * @param nextPageLink the link to the next page. + * @return this Page object itself. + */ + public PageImpl setNextPageLink(String nextPageLink) { + this.nextPageLink = nextPageLink; + return this; + } + + /** + * Sets the list of items. + * + * @param items the list of items in {@link List}. + * @return this Page object itself. + */ + public PageImpl setItems(List items) { + this.items = items; + return this; + } +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventInner.java new file mode 100644 index 0000000000000..52e79bbcadc6b --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventInner.java @@ -0,0 +1,809 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import java.util.Map; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Policy event record. + */ +public class PolicyEventInner { + /** + * Unmatched properties from the message are deserialized this collection. + */ + @JsonProperty(value = "") + private Map additionalProperties; + + /** + * OData entity ID; always set to null since policy event records do not + * have an entity ID. + */ + @JsonProperty(value = "@odata\\.id") + private String odataid; + + /** + * OData context string; used by OData clients to resolve type information + * based on metadata. + */ + @JsonProperty(value = "@odata\\.context") + private String odatacontext; + + /** + * Timestamp for the policy event record. + */ + @JsonProperty(value = "timestamp") + private DateTime timestamp; + + /** + * Resource ID. + */ + @JsonProperty(value = "resourceId") + private String resourceId; + + /** + * Policy assignment ID. + */ + @JsonProperty(value = "policyAssignmentId") + private String policyAssignmentId; + + /** + * Policy definition ID. + */ + @JsonProperty(value = "policyDefinitionId") + private String policyDefinitionId; + + /** + * Effective parameters for the policy assignment. + */ + @JsonProperty(value = "effectiveParameters") + private String effectiveParameters; + + /** + * Flag which states whether the resource is compliant against the policy + * assignment it was evaluated against. + */ + @JsonProperty(value = "isCompliant") + private Boolean isCompliant; + + /** + * Subscription ID. + */ + @JsonProperty(value = "subscriptionId") + private String subscriptionId; + + /** + * Resource type. + */ + @JsonProperty(value = "resourceType") + private String resourceType; + + /** + * Resource location. + */ + @JsonProperty(value = "resourceLocation") + private String resourceLocation; + + /** + * Resource group name. + */ + @JsonProperty(value = "resourceGroup") + private String resourceGroup; + + /** + * List of resource tags. + */ + @JsonProperty(value = "resourceTags") + private String resourceTags; + + /** + * Policy assignment name. + */ + @JsonProperty(value = "policyAssignmentName") + private String policyAssignmentName; + + /** + * Policy assignment owner. + */ + @JsonProperty(value = "policyAssignmentOwner") + private String policyAssignmentOwner; + + /** + * Policy assignment parameters. + */ + @JsonProperty(value = "policyAssignmentParameters") + private String policyAssignmentParameters; + + /** + * Policy assignment scope. + */ + @JsonProperty(value = "policyAssignmentScope") + private String policyAssignmentScope; + + /** + * Policy definition name. + */ + @JsonProperty(value = "policyDefinitionName") + private String policyDefinitionName; + + /** + * Policy definition action, i.e. effect. + */ + @JsonProperty(value = "policyDefinitionAction") + private String policyDefinitionAction; + + /** + * Policy definition category. + */ + @JsonProperty(value = "policyDefinitionCategory") + private String policyDefinitionCategory; + + /** + * Policy set definition ID, if the policy assignment is for a policy set. + */ + @JsonProperty(value = "policySetDefinitionId") + private String policySetDefinitionId; + + /** + * Policy set definition name, if the policy assignment is for a policy + * set. + */ + @JsonProperty(value = "policySetDefinitionName") + private String policySetDefinitionName; + + /** + * Policy set definition owner, if the policy assignment is for a policy + * set. + */ + @JsonProperty(value = "policySetDefinitionOwner") + private String policySetDefinitionOwner; + + /** + * Policy set definition category, if the policy assignment is for a policy + * set. + */ + @JsonProperty(value = "policySetDefinitionCategory") + private String policySetDefinitionCategory; + + /** + * Policy set definition parameters, if the policy assignment is for a + * policy set. + */ + @JsonProperty(value = "policySetDefinitionParameters") + private String policySetDefinitionParameters; + + /** + * Comma separated list of management group IDs, which represent the + * hierarchy of the management groups the resource is under. + */ + @JsonProperty(value = "managementGroupIds") + private String managementGroupIds; + + /** + * Reference ID for the policy definition inside the policy set, if the + * policy assignment is for a policy set. + */ + @JsonProperty(value = "policyDefinitionReferenceId") + private String policyDefinitionReferenceId; + + /** + * Tenant ID for the policy event record. + */ + @JsonProperty(value = "tenantId") + private String tenantId; + + /** + * Principal object ID for the user who initiated the resource operation + * that triggered the policy event. + */ + @JsonProperty(value = "principalOid") + private String principalOid; + + /** + * Get unmatched properties from the message are deserialized this collection. + * + * @return the additionalProperties value + */ + public Map additionalProperties() { + return this.additionalProperties; + } + + /** + * Set unmatched properties from the message are deserialized this collection. + * + * @param additionalProperties the additionalProperties value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } + + /** + * Get oData entity ID; always set to null since policy event records do not have an entity ID. + * + * @return the odataid value + */ + public String odataid() { + return this.odataid; + } + + /** + * Set oData entity ID; always set to null since policy event records do not have an entity ID. + * + * @param odataid the odataid value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withOdataid(String odataid) { + this.odataid = odataid; + return this; + } + + /** + * Get oData context string; used by OData clients to resolve type information based on metadata. + * + * @return the odatacontext value + */ + public String odatacontext() { + return this.odatacontext; + } + + /** + * Set oData context string; used by OData clients to resolve type information based on metadata. + * + * @param odatacontext the odatacontext value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withOdatacontext(String odatacontext) { + this.odatacontext = odatacontext; + return this; + } + + /** + * Get timestamp for the policy event record. + * + * @return the timestamp value + */ + public DateTime timestamp() { + return this.timestamp; + } + + /** + * Set timestamp for the policy event record. + * + * @param timestamp the timestamp value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withTimestamp(DateTime timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * Get resource ID. + * + * @return the resourceId value + */ + public String resourceId() { + return this.resourceId; + } + + /** + * Set resource ID. + * + * @param resourceId the resourceId value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withResourceId(String resourceId) { + this.resourceId = resourceId; + return this; + } + + /** + * Get policy assignment ID. + * + * @return the policyAssignmentId value + */ + public String policyAssignmentId() { + return this.policyAssignmentId; + } + + /** + * Set policy assignment ID. + * + * @param policyAssignmentId the policyAssignmentId value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyAssignmentId(String policyAssignmentId) { + this.policyAssignmentId = policyAssignmentId; + return this; + } + + /** + * Get policy definition ID. + * + * @return the policyDefinitionId value + */ + public String policyDefinitionId() { + return this.policyDefinitionId; + } + + /** + * Set policy definition ID. + * + * @param policyDefinitionId the policyDefinitionId value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyDefinitionId(String policyDefinitionId) { + this.policyDefinitionId = policyDefinitionId; + return this; + } + + /** + * Get effective parameters for the policy assignment. + * + * @return the effectiveParameters value + */ + public String effectiveParameters() { + return this.effectiveParameters; + } + + /** + * Set effective parameters for the policy assignment. + * + * @param effectiveParameters the effectiveParameters value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withEffectiveParameters(String effectiveParameters) { + this.effectiveParameters = effectiveParameters; + return this; + } + + /** + * Get flag which states whether the resource is compliant against the policy assignment it was evaluated against. + * + * @return the isCompliant value + */ + public Boolean isCompliant() { + return this.isCompliant; + } + + /** + * Set flag which states whether the resource is compliant against the policy assignment it was evaluated against. + * + * @param isCompliant the isCompliant value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withIsCompliant(Boolean isCompliant) { + this.isCompliant = isCompliant; + return this; + } + + /** + * Get subscription ID. + * + * @return the subscriptionId value + */ + public String subscriptionId() { + return this.subscriptionId; + } + + /** + * Set subscription ID. + * + * @param subscriptionId the subscriptionId value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /** + * Get resource type. + * + * @return the resourceType value + */ + public String resourceType() { + return this.resourceType; + } + + /** + * Set resource type. + * + * @param resourceType the resourceType value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withResourceType(String resourceType) { + this.resourceType = resourceType; + return this; + } + + /** + * Get resource location. + * + * @return the resourceLocation value + */ + public String resourceLocation() { + return this.resourceLocation; + } + + /** + * Set resource location. + * + * @param resourceLocation the resourceLocation value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withResourceLocation(String resourceLocation) { + this.resourceLocation = resourceLocation; + return this; + } + + /** + * Get resource group name. + * + * @return the resourceGroup value + */ + public String resourceGroup() { + return this.resourceGroup; + } + + /** + * Set resource group name. + * + * @param resourceGroup the resourceGroup value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withResourceGroup(String resourceGroup) { + this.resourceGroup = resourceGroup; + return this; + } + + /** + * Get list of resource tags. + * + * @return the resourceTags value + */ + public String resourceTags() { + return this.resourceTags; + } + + /** + * Set list of resource tags. + * + * @param resourceTags the resourceTags value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withResourceTags(String resourceTags) { + this.resourceTags = resourceTags; + return this; + } + + /** + * Get policy assignment name. + * + * @return the policyAssignmentName value + */ + public String policyAssignmentName() { + return this.policyAssignmentName; + } + + /** + * Set policy assignment name. + * + * @param policyAssignmentName the policyAssignmentName value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyAssignmentName(String policyAssignmentName) { + this.policyAssignmentName = policyAssignmentName; + return this; + } + + /** + * Get policy assignment owner. + * + * @return the policyAssignmentOwner value + */ + public String policyAssignmentOwner() { + return this.policyAssignmentOwner; + } + + /** + * Set policy assignment owner. + * + * @param policyAssignmentOwner the policyAssignmentOwner value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyAssignmentOwner(String policyAssignmentOwner) { + this.policyAssignmentOwner = policyAssignmentOwner; + return this; + } + + /** + * Get policy assignment parameters. + * + * @return the policyAssignmentParameters value + */ + public String policyAssignmentParameters() { + return this.policyAssignmentParameters; + } + + /** + * Set policy assignment parameters. + * + * @param policyAssignmentParameters the policyAssignmentParameters value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyAssignmentParameters(String policyAssignmentParameters) { + this.policyAssignmentParameters = policyAssignmentParameters; + return this; + } + + /** + * Get policy assignment scope. + * + * @return the policyAssignmentScope value + */ + public String policyAssignmentScope() { + return this.policyAssignmentScope; + } + + /** + * Set policy assignment scope. + * + * @param policyAssignmentScope the policyAssignmentScope value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyAssignmentScope(String policyAssignmentScope) { + this.policyAssignmentScope = policyAssignmentScope; + return this; + } + + /** + * Get policy definition name. + * + * @return the policyDefinitionName value + */ + public String policyDefinitionName() { + return this.policyDefinitionName; + } + + /** + * Set policy definition name. + * + * @param policyDefinitionName the policyDefinitionName value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyDefinitionName(String policyDefinitionName) { + this.policyDefinitionName = policyDefinitionName; + return this; + } + + /** + * Get policy definition action, i.e. effect. + * + * @return the policyDefinitionAction value + */ + public String policyDefinitionAction() { + return this.policyDefinitionAction; + } + + /** + * Set policy definition action, i.e. effect. + * + * @param policyDefinitionAction the policyDefinitionAction value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyDefinitionAction(String policyDefinitionAction) { + this.policyDefinitionAction = policyDefinitionAction; + return this; + } + + /** + * Get policy definition category. + * + * @return the policyDefinitionCategory value + */ + public String policyDefinitionCategory() { + return this.policyDefinitionCategory; + } + + /** + * Set policy definition category. + * + * @param policyDefinitionCategory the policyDefinitionCategory value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyDefinitionCategory(String policyDefinitionCategory) { + this.policyDefinitionCategory = policyDefinitionCategory; + return this; + } + + /** + * Get policy set definition ID, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionId value + */ + public String policySetDefinitionId() { + return this.policySetDefinitionId; + } + + /** + * Set policy set definition ID, if the policy assignment is for a policy set. + * + * @param policySetDefinitionId the policySetDefinitionId value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicySetDefinitionId(String policySetDefinitionId) { + this.policySetDefinitionId = policySetDefinitionId; + return this; + } + + /** + * Get policy set definition name, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionName value + */ + public String policySetDefinitionName() { + return this.policySetDefinitionName; + } + + /** + * Set policy set definition name, if the policy assignment is for a policy set. + * + * @param policySetDefinitionName the policySetDefinitionName value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicySetDefinitionName(String policySetDefinitionName) { + this.policySetDefinitionName = policySetDefinitionName; + return this; + } + + /** + * Get policy set definition owner, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionOwner value + */ + public String policySetDefinitionOwner() { + return this.policySetDefinitionOwner; + } + + /** + * Set policy set definition owner, if the policy assignment is for a policy set. + * + * @param policySetDefinitionOwner the policySetDefinitionOwner value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicySetDefinitionOwner(String policySetDefinitionOwner) { + this.policySetDefinitionOwner = policySetDefinitionOwner; + return this; + } + + /** + * Get policy set definition category, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionCategory value + */ + public String policySetDefinitionCategory() { + return this.policySetDefinitionCategory; + } + + /** + * Set policy set definition category, if the policy assignment is for a policy set. + * + * @param policySetDefinitionCategory the policySetDefinitionCategory value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicySetDefinitionCategory(String policySetDefinitionCategory) { + this.policySetDefinitionCategory = policySetDefinitionCategory; + return this; + } + + /** + * Get policy set definition parameters, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionParameters value + */ + public String policySetDefinitionParameters() { + return this.policySetDefinitionParameters; + } + + /** + * Set policy set definition parameters, if the policy assignment is for a policy set. + * + * @param policySetDefinitionParameters the policySetDefinitionParameters value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicySetDefinitionParameters(String policySetDefinitionParameters) { + this.policySetDefinitionParameters = policySetDefinitionParameters; + return this; + } + + /** + * Get comma separated list of management group IDs, which represent the hierarchy of the management groups the resource is under. + * + * @return the managementGroupIds value + */ + public String managementGroupIds() { + return this.managementGroupIds; + } + + /** + * Set comma separated list of management group IDs, which represent the hierarchy of the management groups the resource is under. + * + * @param managementGroupIds the managementGroupIds value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withManagementGroupIds(String managementGroupIds) { + this.managementGroupIds = managementGroupIds; + return this; + } + + /** + * Get reference ID for the policy definition inside the policy set, if the policy assignment is for a policy set. + * + * @return the policyDefinitionReferenceId value + */ + public String policyDefinitionReferenceId() { + return this.policyDefinitionReferenceId; + } + + /** + * Set reference ID for the policy definition inside the policy set, if the policy assignment is for a policy set. + * + * @param policyDefinitionReferenceId the policyDefinitionReferenceId value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPolicyDefinitionReferenceId(String policyDefinitionReferenceId) { + this.policyDefinitionReferenceId = policyDefinitionReferenceId; + return this; + } + + /** + * Get tenant ID for the policy event record. + * + * @return the tenantId value + */ + public String tenantId() { + return this.tenantId; + } + + /** + * Set tenant ID for the policy event record. + * + * @param tenantId the tenantId value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withTenantId(String tenantId) { + this.tenantId = tenantId; + return this; + } + + /** + * Get principal object ID for the user who initiated the resource operation that triggered the policy event. + * + * @return the principalOid value + */ + public String principalOid() { + return this.principalOid; + } + + /** + * Set principal object ID for the user who initiated the resource operation that triggered the policy event. + * + * @param principalOid the principalOid value to set + * @return the PolicyEventInner object itself. + */ + public PolicyEventInner withPrincipalOid(String principalOid) { + this.principalOid = principalOid; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsImpl.java new file mode 100644 index 0000000000000..9ec4f34bd53cf --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsImpl.java @@ -0,0 +1,132 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEventsQueryResults; + +class PolicyEventsImpl extends WrapperImpl implements PolicyEvents { + private final PolicyInsightsManager manager; + + PolicyEventsImpl(PolicyInsightsManager manager) { + super(manager.inner().policyEvents()); + this.manager = manager; + } + + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public Observable listQueryResultsForManagementGroupAsync(String managementGroupName) { + PolicyEventsInner client = this.inner(); + return client.listQueryResultsForManagementGroupAsync(managementGroupName) + .map(new Func1() { + @Override + public PolicyEventsQueryResults call(PolicyEventsQueryResultsInner inner) { + return new PolicyEventsQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForSubscriptionAsync(String subscriptionId) { + PolicyEventsInner client = this.inner(); + return client.listQueryResultsForSubscriptionAsync(subscriptionId) + .map(new Func1() { + @Override + public PolicyEventsQueryResults call(PolicyEventsQueryResultsInner inner) { + return new PolicyEventsQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForResourceGroupAsync(String subscriptionId, String resourceGroupName) { + PolicyEventsInner client = this.inner(); + return client.listQueryResultsForResourceGroupAsync(subscriptionId, resourceGroupName) + .map(new Func1() { + @Override + public PolicyEventsQueryResults call(PolicyEventsQueryResultsInner inner) { + return new PolicyEventsQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForResourceAsync(String resourceId) { + PolicyEventsInner client = this.inner(); + return client.listQueryResultsForResourceAsync(resourceId) + .map(new Func1() { + @Override + public PolicyEventsQueryResults call(PolicyEventsQueryResultsInner inner) { + return new PolicyEventsQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName) { + PolicyEventsInner client = this.inner(); + return client.listQueryResultsForPolicySetDefinitionAsync(subscriptionId, policySetDefinitionName) + .map(new Func1() { + @Override + public PolicyEventsQueryResults call(PolicyEventsQueryResultsInner inner) { + return new PolicyEventsQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName) { + PolicyEventsInner client = this.inner(); + return client.listQueryResultsForPolicyDefinitionAsync(subscriptionId, policyDefinitionName) + .map(new Func1() { + @Override + public PolicyEventsQueryResults call(PolicyEventsQueryResultsInner inner) { + return new PolicyEventsQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName) { + PolicyEventsInner client = this.inner(); + return client.listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(subscriptionId, policyAssignmentName) + .map(new Func1() { + @Override + public PolicyEventsQueryResults call(PolicyEventsQueryResultsInner inner) { + return new PolicyEventsQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName) { + PolicyEventsInner client = this.inner(); + return client.listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(subscriptionId, resourceGroupName, policyAssignmentName) + .map(new Func1() { + @Override + public PolicyEventsQueryResults call(PolicyEventsQueryResultsInner inner) { + return new PolicyEventsQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable getMetadataAsync(String scope) { + PolicyEventsInner client = this.inner(); + return client.getMetadataAsync(scope) + ;} + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsInner.java new file mode 100644 index 0000000000000..d8ff1f941b714 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsInner.java @@ -0,0 +1,1736 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.management.policyinsights.v2019_10_01.QueryFailureException; +import com.microsoft.azure.management.policyinsights.v2019_10_01.QueryOptions; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import okhttp3.ResponseBody; +import org.joda.time.DateTime; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in PolicyEvents. + */ +public class PolicyEventsInner { + /** The Retrofit service to perform REST calls. */ + private PolicyEventsService service; + /** The service client containing this operation class. */ + private PolicyInsightsClientImpl client; + + /** + * Initializes an instance of PolicyEventsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public PolicyEventsInner(Retrofit retrofit, PolicyInsightsClientImpl client) { + this.service = retrofit.create(PolicyEventsService.class); + this.client = client; + } + + /** + * The interface defining all the services for PolicyEvents to be + * used by Retrofit to perform actually REST calls. + */ + interface PolicyEventsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents listQueryResultsForManagementGroup" }) + @POST("providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults") + Observable> listQueryResultsForManagementGroup(@Path("policyEventsResource") String policyEventsResource, @Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupName") String managementGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents listQueryResultsForSubscription" }) + @POST("subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults") + Observable> listQueryResultsForSubscription(@Path("policyEventsResource") String policyEventsResource, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents listQueryResultsForResourceGroup" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults") + Observable> listQueryResultsForResourceGroup(@Path("policyEventsResource") String policyEventsResource, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents listQueryResultsForResource" }) + @POST("{resourceId}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults") + Observable> listQueryResultsForResource(@Path("policyEventsResource") String policyEventsResource, @Path(value = "resourceId", encoded = true) String resourceId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents listQueryResultsForPolicySetDefinition" }) + @POST("subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults") + Observable> listQueryResultsForPolicySetDefinition(@Path("policyEventsResource") String policyEventsResource, @Path("subscriptionId") String subscriptionId, @Path("authorizationNamespace") String authorizationNamespace, @Path("policySetDefinitionName") String policySetDefinitionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents listQueryResultsForPolicyDefinition" }) + @POST("subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults") + Observable> listQueryResultsForPolicyDefinition(@Path("policyEventsResource") String policyEventsResource, @Path("subscriptionId") String subscriptionId, @Path("authorizationNamespace") String authorizationNamespace, @Path("policyDefinitionName") String policyDefinitionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents listQueryResultsForSubscriptionLevelPolicyAssignment" }) + @POST("subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults") + Observable> listQueryResultsForSubscriptionLevelPolicyAssignment(@Path("policyEventsResource") String policyEventsResource, @Path("subscriptionId") String subscriptionId, @Path("authorizationNamespace") String authorizationNamespace, @Path("policyAssignmentName") String policyAssignmentName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents listQueryResultsForResourceGroupLevelPolicyAssignment" }) + @POST("subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyEvents/{policyEventsResource}/queryResults") + Observable> listQueryResultsForResourceGroupLevelPolicyAssignment(@Path("policyEventsResource") String policyEventsResource, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("authorizationNamespace") String authorizationNamespace, @Path("policyAssignmentName") String policyAssignmentName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents getMetadata" }) + @GET("{scope}/providers/Microsoft.PolicyInsights/policyEvents/$metadata") + Observable> getMetadata(@Path(value = "scope", encoded = true) String scope, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Queries policy events for the resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForManagementGroup(String managementGroupName) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(managementGroupName).toBlocking().single().body(); + } + + /** + * Queries policy events for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForManagementGroupAsync(String managementGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForManagementGroupWithServiceResponseAsync(managementGroupName), serviceCallback); + } + + /** + * Queries policy events for the resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForManagementGroupAsync(String managementGroupName) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(managementGroupName).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForManagementGroupWithServiceResponseAsync(String managementGroupName) { + if (managementGroupName == null) { + throw new IllegalArgumentException("Parameter managementGroupName is required and cannot be null."); + } + final String policyEventsResource = "default"; + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2018-04-04"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForManagementGroup(policyEventsResource, managementGroupsNamespace, managementGroupName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy events for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForManagementGroup(String managementGroupName, QueryOptions queryOptions) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(managementGroupName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy events for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForManagementGroupAsync(String managementGroupName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForManagementGroupWithServiceResponseAsync(managementGroupName, queryOptions), serviceCallback); + } + + /** + * Queries policy events for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForManagementGroupAsync(String managementGroupName, QueryOptions queryOptions) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(managementGroupName, queryOptions).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForManagementGroupWithServiceResponseAsync(String managementGroupName, QueryOptions queryOptions) { + if (managementGroupName == null) { + throw new IllegalArgumentException("Parameter managementGroupName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyEventsResource = "default"; + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2018-04-04"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForManagementGroup(policyEventsResource, managementGroupsNamespace, managementGroupName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForManagementGroupDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy events for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForSubscription(String subscriptionId) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(subscriptionId).toBlocking().single().body(); + } + + /** + * Queries policy events for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForSubscriptionAsync(String subscriptionId, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForSubscriptionWithServiceResponseAsync(subscriptionId), serviceCallback); + } + + /** + * Queries policy events for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForSubscriptionAsync(String subscriptionId) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(subscriptionId).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForSubscriptionWithServiceResponseAsync(String subscriptionId) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + final String policyEventsResource = "default"; + final String apiVersion = "2018-04-04"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForSubscription(policyEventsResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy events for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForSubscription(String subscriptionId, QueryOptions queryOptions) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(subscriptionId, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy events for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForSubscriptionAsync(String subscriptionId, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForSubscriptionWithServiceResponseAsync(subscriptionId, queryOptions), serviceCallback); + } + + /** + * Queries policy events for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForSubscriptionAsync(String subscriptionId, QueryOptions queryOptions) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(subscriptionId, queryOptions).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForSubscriptionWithServiceResponseAsync(String subscriptionId, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyEventsResource = "default"; + final String apiVersion = "2018-04-04"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForSubscription(policyEventsResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForSubscriptionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy events for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForResourceGroup(String subscriptionId, String resourceGroupName) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName).toBlocking().single().body(); + } + + /** + * Queries policy events for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceGroupAsync(String subscriptionId, String resourceGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName), serviceCallback); + } + + /** + * Queries policy events for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForResourceGroupAsync(String subscriptionId, String resourceGroupName) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForResourceGroupWithServiceResponseAsync(String subscriptionId, String resourceGroupName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + final String policyEventsResource = "default"; + final String apiVersion = "2018-04-04"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForResourceGroup(policyEventsResource, subscriptionId, resourceGroupName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy events for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForResourceGroup(String subscriptionId, String resourceGroupName, QueryOptions queryOptions) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy events for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceGroupAsync(String subscriptionId, String resourceGroupName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, queryOptions), serviceCallback); + } + + /** + * Queries policy events for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForResourceGroupAsync(String subscriptionId, String resourceGroupName, QueryOptions queryOptions) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, queryOptions).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForResourceGroupWithServiceResponseAsync(String subscriptionId, String resourceGroupName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyEventsResource = "default"; + final String apiVersion = "2018-04-04"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForResourceGroup(policyEventsResource, subscriptionId, resourceGroupName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForResourceGroupDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy events for the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForResource(String resourceId) { + return listQueryResultsForResourceWithServiceResponseAsync(resourceId).toBlocking().single().body(); + } + + /** + * Queries policy events for the resource. + * + * @param resourceId Resource ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceAsync(String resourceId, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceWithServiceResponseAsync(resourceId), serviceCallback); + } + + /** + * Queries policy events for the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForResourceAsync(String resourceId) { + return listQueryResultsForResourceWithServiceResponseAsync(resourceId).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForResourceWithServiceResponseAsync(String resourceId) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + final String policyEventsResource = "default"; + final String apiVersion = "2018-04-04"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForResource(policyEventsResource, resourceId, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy events for the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForResource(String resourceId, QueryOptions queryOptions) { + return listQueryResultsForResourceWithServiceResponseAsync(resourceId, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy events for the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceAsync(String resourceId, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceWithServiceResponseAsync(resourceId, queryOptions), serviceCallback); + } + + /** + * Queries policy events for the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForResourceAsync(String resourceId, QueryOptions queryOptions) { + return listQueryResultsForResourceWithServiceResponseAsync(resourceId, queryOptions).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForResourceWithServiceResponseAsync(String resourceId, QueryOptions queryOptions) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyEventsResource = "default"; + final String apiVersion = "2018-04-04"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForResource(policyEventsResource, resourceId, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForResourceDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy events for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForPolicySetDefinition(String subscriptionId, String policySetDefinitionName) { + return listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName).toBlocking().single().body(); + } + + /** + * Queries policy events for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName), serviceCallback); + } + + /** + * Queries policy events for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName) { + return listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(String subscriptionId, String policySetDefinitionName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policySetDefinitionName == null) { + throw new IllegalArgumentException("Parameter policySetDefinitionName is required and cannot be null."); + } + final String policyEventsResource = "default"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2018-04-04"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForPolicySetDefinition(policyEventsResource, subscriptionId, authorizationNamespace, policySetDefinitionName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForPolicySetDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy events for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForPolicySetDefinition(String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions) { + return listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy events for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName, queryOptions), serviceCallback); + } + + /** + * Queries policy events for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions) { + return listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName, queryOptions).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policySetDefinitionName == null) { + throw new IllegalArgumentException("Parameter policySetDefinitionName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyEventsResource = "default"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2018-04-04"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForPolicySetDefinition(policyEventsResource, subscriptionId, authorizationNamespace, policySetDefinitionName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForPolicySetDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForPolicySetDefinitionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy events for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForPolicyDefinition(String subscriptionId, String policyDefinitionName) { + return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName).toBlocking().single().body(); + } + + /** + * Queries policy events for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName), serviceCallback); + } + + /** + * Queries policy events for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName) { + return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForPolicyDefinitionWithServiceResponseAsync(String subscriptionId, String policyDefinitionName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyDefinitionName == null) { + throw new IllegalArgumentException("Parameter policyDefinitionName is required and cannot be null."); + } + final String policyEventsResource = "default"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2018-04-04"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForPolicyDefinition(policyEventsResource, subscriptionId, authorizationNamespace, policyDefinitionName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForPolicyDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy events for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForPolicyDefinition(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { + return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy events for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions), serviceCallback); + } + + /** + * Queries policy events for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { + return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForPolicyDefinitionWithServiceResponseAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyDefinitionName == null) { + throw new IllegalArgumentException("Parameter policyDefinitionName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyEventsResource = "default"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2018-04-04"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForPolicyDefinition(policyEventsResource, subscriptionId, authorizationNamespace, policyDefinitionName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForPolicyDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForPolicyDefinitionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy events for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForSubscriptionLevelPolicyAssignment(String subscriptionId, String policyAssignmentName) { + return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName).toBlocking().single().body(); + } + + /** + * Queries policy events for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName), serviceCallback); + } + + /** + * Queries policy events for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName) { + return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(String subscriptionId, String policyAssignmentName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + final String policyEventsResource = "default"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2018-04-04"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForSubscriptionLevelPolicyAssignment(policyEventsResource, subscriptionId, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForSubscriptionLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy events for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForSubscriptionLevelPolicyAssignment(String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) { + return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy events for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName, queryOptions), serviceCallback); + } + + /** + * Queries policy events for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) { + return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName, queryOptions).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyEventsResource = "default"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2018-04-04"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForSubscriptionLevelPolicyAssignment(policyEventsResource, subscriptionId, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForSubscriptionLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForSubscriptionLevelPolicyAssignmentDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy events for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForResourceGroupLevelPolicyAssignment(String subscriptionId, String resourceGroupName, String policyAssignmentName) { + return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName).toBlocking().single().body(); + } + + /** + * Queries policy events for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName), serviceCallback); + } + + /** + * Queries policy events for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName) { + return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + final String policyEventsResource = "default"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2018-04-04"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForResourceGroupLevelPolicyAssignment(policyEventsResource, subscriptionId, resourceGroupName, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceGroupLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy events for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyEventsQueryResultsInner object if successful. + */ + public PolicyEventsQueryResultsInner listQueryResultsForResourceGroupLevelPolicyAssignment(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) { + return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy events for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName, queryOptions), serviceCallback); + } + + /** + * Queries policy events for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) { + return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName, queryOptions).map(new Func1, PolicyEventsQueryResultsInner>() { + @Override + public PolicyEventsQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy events for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyEventsQueryResultsInner object + */ + public Observable> listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyEventsResource = "default"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2018-04-04"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForResourceGroupLevelPolicyAssignment(policyEventsResource, subscriptionId, resourceGroupName, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceGroupLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForResourceGroupLevelPolicyAssignmentDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Gets OData metadata XML document. + * + * @param scope A valid scope, i.e. management group, subscription, resource group, or resource ID. Scope used has no effect on metadata returned. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the String object if successful. + */ + public String getMetadata(String scope) { + return getMetadataWithServiceResponseAsync(scope).toBlocking().single().body(); + } + + /** + * Gets OData metadata XML document. + * + * @param scope A valid scope, i.e. management group, subscription, resource group, or resource ID. Scope used has no effect on metadata returned. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getMetadataAsync(String scope, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getMetadataWithServiceResponseAsync(scope), serviceCallback); + } + + /** + * Gets OData metadata XML document. + * + * @param scope A valid scope, i.e. management group, subscription, resource group, or resource ID. Scope used has no effect on metadata returned. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the String object + */ + public Observable getMetadataAsync(String scope) { + return getMetadataWithServiceResponseAsync(scope).map(new Func1, String>() { + @Override + public String call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets OData metadata XML document. + * + * @param scope A valid scope, i.e. management group, subscription, resource group, or resource ID. Scope used has no effect on metadata returned. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the String object + */ + public Observable> getMetadataWithServiceResponseAsync(String scope) { + if (scope == null) { + throw new IllegalArgumentException("Parameter scope is required and cannot be null."); + } + final String apiVersion = "2018-04-04"; + return service.getMetadata(scope, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getMetadataDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getMetadataDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsQueryResultsImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsQueryResultsImpl.java new file mode 100644 index 0000000000000..a99d7962fce86 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsQueryResultsImpl.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEventsQueryResults; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import java.util.List; + +class PolicyEventsQueryResultsImpl extends WrapperImpl implements PolicyEventsQueryResults { + private final PolicyInsightsManager manager; + PolicyEventsQueryResultsImpl(PolicyEventsQueryResultsInner inner, PolicyInsightsManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public String odatacontext() { + return this.inner().odatacontext(); + } + + @Override + public Integer odatacount() { + return this.inner().odatacount(); + } + + @Override + public List value() { + return this.inner().value(); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsQueryResultsInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsQueryResultsInner.java new file mode 100644 index 0000000000000..e932164aabad6 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyEventsQueryResultsInner.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Query results. + */ +public class PolicyEventsQueryResultsInner { + /** + * OData context string; used by OData clients to resolve type information + * based on metadata. + */ + @JsonProperty(value = "@odata\\.context") + private String odatacontext; + + /** + * OData entity count; represents the number of policy event records + * returned. + */ + @JsonProperty(value = "@odata\\.count") + private Integer odatacount; + + /** + * Query results. + */ + @JsonProperty(value = "value") + private List value; + + /** + * Get oData context string; used by OData clients to resolve type information based on metadata. + * + * @return the odatacontext value + */ + public String odatacontext() { + return this.odatacontext; + } + + /** + * Set oData context string; used by OData clients to resolve type information based on metadata. + * + * @param odatacontext the odatacontext value to set + * @return the PolicyEventsQueryResultsInner object itself. + */ + public PolicyEventsQueryResultsInner withOdatacontext(String odatacontext) { + this.odatacontext = odatacontext; + return this; + } + + /** + * Get oData entity count; represents the number of policy event records returned. + * + * @return the odatacount value + */ + public Integer odatacount() { + return this.odatacount; + } + + /** + * Set oData entity count; represents the number of policy event records returned. + * + * @param odatacount the odatacount value to set + * @return the PolicyEventsQueryResultsInner object itself. + */ + public PolicyEventsQueryResultsInner withOdatacount(Integer odatacount) { + this.odatacount = odatacount; + return this; + } + + /** + * Get query results. + * + * @return the value value + */ + public List value() { + return this.value; + } + + /** + * Set query results. + * + * @param value the value value to set + * @return the PolicyEventsQueryResultsInner object itself. + */ + public PolicyEventsQueryResultsInner withValue(List value) { + this.value = value; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyInsightsClientImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyInsightsClientImpl.java new file mode 100644 index 0000000000000..074ac33762e28 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyInsightsClientImpl.java @@ -0,0 +1,230 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.AzureClient; +import com.microsoft.azure.AzureServiceClient; +import com.microsoft.rest.credentials.ServiceClientCredentials; +import com.microsoft.rest.RestClient; + +/** + * Initializes a new instance of the PolicyInsightsClientImpl class. + */ +public class PolicyInsightsClientImpl extends AzureServiceClient { + /** the {@link AzureClient} used for long running operations. */ + private AzureClient azureClient; + + /** + * Gets the {@link AzureClient} used for long running operations. + * @return the azure client; + */ + public AzureClient getAzureClient() { + return this.azureClient; + } + + /** The preferred language for the response. */ + private String acceptLanguage; + + /** + * Gets The preferred language for the response. + * + * @return the acceptLanguage value. + */ + public String acceptLanguage() { + return this.acceptLanguage; + } + + /** + * Sets The preferred language for the response. + * + * @param acceptLanguage the acceptLanguage value. + * @return the service client itself + */ + public PolicyInsightsClientImpl withAcceptLanguage(String acceptLanguage) { + this.acceptLanguage = acceptLanguage; + return this; + } + + /** The retry timeout in seconds for Long Running Operations. Default value is 30. */ + private int longRunningOperationRetryTimeout; + + /** + * Gets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @return the longRunningOperationRetryTimeout value. + */ + public int longRunningOperationRetryTimeout() { + return this.longRunningOperationRetryTimeout; + } + + /** + * Sets The retry timeout in seconds for Long Running Operations. Default value is 30. + * + * @param longRunningOperationRetryTimeout the longRunningOperationRetryTimeout value. + * @return the service client itself + */ + public PolicyInsightsClientImpl withLongRunningOperationRetryTimeout(int longRunningOperationRetryTimeout) { + this.longRunningOperationRetryTimeout = longRunningOperationRetryTimeout; + return this; + } + + /** Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. */ + private boolean generateClientRequestId; + + /** + * Gets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @return the generateClientRequestId value. + */ + public boolean generateClientRequestId() { + return this.generateClientRequestId; + } + + /** + * Sets Whether a unique x-ms-client-request-id should be generated. When set to true a unique x-ms-client-request-id value is generated and included in each request. Default is true. + * + * @param generateClientRequestId the generateClientRequestId value. + * @return the service client itself + */ + public PolicyInsightsClientImpl withGenerateClientRequestId(boolean generateClientRequestId) { + this.generateClientRequestId = generateClientRequestId; + return this; + } + + /** + * The PolicyTrackedResourcesInner object to access its operations. + */ + private PolicyTrackedResourcesInner policyTrackedResources; + + /** + * Gets the PolicyTrackedResourcesInner object to access its operations. + * @return the PolicyTrackedResourcesInner object. + */ + public PolicyTrackedResourcesInner policyTrackedResources() { + return this.policyTrackedResources; + } + + /** + * The RemediationsInner object to access its operations. + */ + private RemediationsInner remediations; + + /** + * Gets the RemediationsInner object to access its operations. + * @return the RemediationsInner object. + */ + public RemediationsInner remediations() { + return this.remediations; + } + + /** + * The PolicyEventsInner object to access its operations. + */ + private PolicyEventsInner policyEvents; + + /** + * Gets the PolicyEventsInner object to access its operations. + * @return the PolicyEventsInner object. + */ + public PolicyEventsInner policyEvents() { + return this.policyEvents; + } + + /** + * The PolicyStatesInner object to access its operations. + */ + private PolicyStatesInner policyStates; + + /** + * Gets the PolicyStatesInner object to access its operations. + * @return the PolicyStatesInner object. + */ + public PolicyStatesInner policyStates() { + return this.policyStates; + } + + /** + * The OperationsInner object to access its operations. + */ + private OperationsInner operations; + + /** + * Gets the OperationsInner object to access its operations. + * @return the OperationsInner object. + */ + public OperationsInner operations() { + return this.operations; + } + + /** + * The PolicyMetadatasInner object to access its operations. + */ + private PolicyMetadatasInner policyMetadatas; + + /** + * Gets the PolicyMetadatasInner object to access its operations. + * @return the PolicyMetadatasInner object. + */ + public PolicyMetadatasInner policyMetadatas() { + return this.policyMetadatas; + } + + /** + * Initializes an instance of PolicyInsightsClient client. + * + * @param credentials the management credentials for Azure + */ + public PolicyInsightsClientImpl(ServiceClientCredentials credentials) { + this("https://management.azure.com", credentials); + } + + /** + * Initializes an instance of PolicyInsightsClient client. + * + * @param baseUrl the base URL of the host + * @param credentials the management credentials for Azure + */ + public PolicyInsightsClientImpl(String baseUrl, ServiceClientCredentials credentials) { + super(baseUrl, credentials); + initialize(); + } + + /** + * Initializes an instance of PolicyInsightsClient client. + * + * @param restClient the REST client to connect to Azure. + */ + public PolicyInsightsClientImpl(RestClient restClient) { + super(restClient); + initialize(); + } + + protected void initialize() { + this.acceptLanguage = "en-US"; + this.longRunningOperationRetryTimeout = 30; + this.generateClientRequestId = true; + this.policyTrackedResources = new PolicyTrackedResourcesInner(restClient().retrofit(), this); + this.remediations = new RemediationsInner(restClient().retrofit(), this); + this.policyEvents = new PolicyEventsInner(restClient().retrofit(), this); + this.policyStates = new PolicyStatesInner(restClient().retrofit(), this); + this.operations = new OperationsInner(restClient().retrofit(), this); + this.policyMetadatas = new PolicyMetadatasInner(restClient().retrofit(), this); + this.azureClient = new AzureClient(this); + } + + /** + * Gets the User-Agent header for the client. + * + * @return the user agent string. + */ + @Override + public String userAgent() { + return String.format("%s (%s, %s, auto-generated)", super.userAgent(), "PolicyInsightsClient", "2019-10-01"); + } +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyInsightsManager.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyInsightsManager.java new file mode 100644 index 0000000000000..6c8774de9f972 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyInsightsManager.java @@ -0,0 +1,156 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.AzureEnvironment; +import com.microsoft.azure.AzureResponseBuilder; +import com.microsoft.azure.credentials.AzureTokenCredentials; +import com.microsoft.azure.management.apigeneration.Beta; +import com.microsoft.azure.management.apigeneration.Beta.SinceVersion; +import com.microsoft.azure.arm.resources.AzureConfigurable; +import com.microsoft.azure.serializer.AzureJacksonAdapter; +import com.microsoft.rest.RestClient; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources; +import com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvents; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates; +import com.microsoft.azure.management.policyinsights.v2019_10_01.Operations; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyMetadatas; +import com.microsoft.azure.arm.resources.implementation.AzureConfigurableCoreImpl; +import com.microsoft.azure.arm.resources.implementation.ManagerCore; + +/** + * Entry point to Azure PolicyInsights resource management. + */ +public final class PolicyInsightsManager extends ManagerCore { + private PolicyTrackedResources policyTrackedResources; + private Remediations remediations; + private PolicyEvents policyEvents; + private PolicyStates policyStates; + private Operations operations; + private PolicyMetadatas policyMetadatas; + /** + * Get a Configurable instance that can be used to create PolicyInsightsManager with optional configuration. + * + * @return the instance allowing configurations + */ + public static Configurable configure() { + return new PolicyInsightsManager.ConfigurableImpl(); + } + /** + * Creates an instance of PolicyInsightsManager that exposes PolicyInsights resource management API entry points. + * + * @param credentials the credentials to use + * @return the PolicyInsightsManager + */ + public static PolicyInsightsManager authenticate(AzureTokenCredentials credentials) { + return new PolicyInsightsManager(new RestClient.Builder() + .withBaseUrl(credentials.environment(), AzureEnvironment.Endpoint.RESOURCE_MANAGER) + .withCredentials(credentials) + .withSerializerAdapter(new AzureJacksonAdapter()) + .withResponseBuilderFactory(new AzureResponseBuilder.Factory()) + .build()); + } + /** + * Creates an instance of PolicyInsightsManager that exposes PolicyInsights resource management API entry points. + * + * @param restClient the RestClient to be used for API calls. + * @return the PolicyInsightsManager + */ + public static PolicyInsightsManager authenticate(RestClient restClient) { + return new PolicyInsightsManager(restClient); + } + /** + * The interface allowing configurations to be set. + */ + public interface Configurable extends AzureConfigurable { + /** + * Creates an instance of PolicyInsightsManager that exposes PolicyInsights management API entry points. + * + * @param credentials the credentials to use + * @return the interface exposing PolicyInsights management API entry points that work across subscriptions + */ + PolicyInsightsManager authenticate(AzureTokenCredentials credentials); + } + + /** + * @return Entry point to manage PolicyTrackedResources. + */ + public PolicyTrackedResources policyTrackedResources() { + if (this.policyTrackedResources == null) { + this.policyTrackedResources = new PolicyTrackedResourcesImpl(this); + } + return this.policyTrackedResources; + } + + /** + * @return Entry point to manage Remediations. + */ + public Remediations remediations() { + if (this.remediations == null) { + this.remediations = new RemediationsImpl(this); + } + return this.remediations; + } + + /** + * @return Entry point to manage PolicyEvents. + */ + public PolicyEvents policyEvents() { + if (this.policyEvents == null) { + this.policyEvents = new PolicyEventsImpl(this); + } + return this.policyEvents; + } + + /** + * @return Entry point to manage PolicyStates. + */ + public PolicyStates policyStates() { + if (this.policyStates == null) { + this.policyStates = new PolicyStatesImpl(this); + } + return this.policyStates; + } + + /** + * @return Entry point to manage Operations. + */ + public Operations operations() { + if (this.operations == null) { + this.operations = new OperationsImpl(this); + } + return this.operations; + } + + /** + * @return Entry point to manage PolicyMetadatas. + */ + public PolicyMetadatas policyMetadatas() { + if (this.policyMetadatas == null) { + this.policyMetadatas = new PolicyMetadatasImpl(this); + } + return this.policyMetadatas; + } + + /** + * The implementation for Configurable interface. + */ + private static final class ConfigurableImpl extends AzureConfigurableCoreImpl implements Configurable { + public PolicyInsightsManager authenticate(AzureTokenCredentials credentials) { + return PolicyInsightsManager.authenticate(buildRestClient(credentials)); + } + } + private PolicyInsightsManager(RestClient restClient) { + super( + restClient, + null, + new PolicyInsightsClientImpl(restClient)); + } +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadataImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadataImpl.java new file mode 100644 index 0000000000000..c7e393582b083 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadataImpl.java @@ -0,0 +1,81 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyMetadata; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; + +class PolicyMetadataImpl extends WrapperImpl implements PolicyMetadata { + private final PolicyInsightsManager manager; + PolicyMetadataImpl(PolicyMetadataInner inner, PolicyInsightsManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public String additionalContentUrl() { + return this.inner().additionalContentUrl(); + } + + @Override + public String category() { + return this.inner().category(); + } + + @Override + public String description() { + return this.inner().description(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public Object metadata() { + return this.inner().metadata(); + } + + @Override + public String metadataId() { + return this.inner().metadataId(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public String owner() { + return this.inner().owner(); + } + + @Override + public String requirements() { + return this.inner().requirements(); + } + + @Override + public String title() { + return this.inner().title(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadataInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadataInner.java new file mode 100644 index 0000000000000..63ff593371658 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadataInner.java @@ -0,0 +1,184 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; + +/** + * Policy metadata resource definition. + */ +@JsonFlatten +public class PolicyMetadataInner { + /** + * The policy metadata identifier. + */ + @JsonProperty(value = "properties.metadataId", access = JsonProperty.Access.WRITE_ONLY) + private String metadataId; + + /** + * The category of the policy metadata. + */ + @JsonProperty(value = "properties.category", access = JsonProperty.Access.WRITE_ONLY) + private String category; + + /** + * The title of the policy metadata. + */ + @JsonProperty(value = "properties.title", access = JsonProperty.Access.WRITE_ONLY) + private String title; + + /** + * The owner of the policy metadata. + */ + @JsonProperty(value = "properties.owner", access = JsonProperty.Access.WRITE_ONLY) + private String owner; + + /** + * Url for getting additional content about the resource metadata. + */ + @JsonProperty(value = "properties.additionalContentUrl", access = JsonProperty.Access.WRITE_ONLY) + private String additionalContentUrl; + + /** + * Additional metadata. + */ + @JsonProperty(value = "properties.metadata", access = JsonProperty.Access.WRITE_ONLY) + private Object metadata; + + /** + * The description of the policy metadata. + */ + @JsonProperty(value = "properties.description", access = JsonProperty.Access.WRITE_ONLY) + private String description; + + /** + * The requirements of the policy metadata. + */ + @JsonProperty(value = "properties.requirements", access = JsonProperty.Access.WRITE_ONLY) + private String requirements; + + /** + * The ID of the policy metadata. + */ + @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) + private String id; + + /** + * The type of the policy metadata. + */ + @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY) + private String type; + + /** + * The name of the policy metadata. + */ + @JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY) + private String name; + + /** + * Get the policy metadata identifier. + * + * @return the metadataId value + */ + public String metadataId() { + return this.metadataId; + } + + /** + * Get the category of the policy metadata. + * + * @return the category value + */ + public String category() { + return this.category; + } + + /** + * Get the title of the policy metadata. + * + * @return the title value + */ + public String title() { + return this.title; + } + + /** + * Get the owner of the policy metadata. + * + * @return the owner value + */ + public String owner() { + return this.owner; + } + + /** + * Get url for getting additional content about the resource metadata. + * + * @return the additionalContentUrl value + */ + public String additionalContentUrl() { + return this.additionalContentUrl; + } + + /** + * Get additional metadata. + * + * @return the metadata value + */ + public Object metadata() { + return this.metadata; + } + + /** + * Get the description of the policy metadata. + * + * @return the description value + */ + public String description() { + return this.description; + } + + /** + * Get the requirements of the policy metadata. + * + * @return the requirements value + */ + public String requirements() { + return this.requirements; + } + + /** + * Get the ID of the policy metadata. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Get the type of the policy metadata. + * + * @return the type value + */ + public String type() { + return this.type; + } + + /** + * Get the name of the policy metadata. + * + * @return the name value + */ + public String name() { + return this.name; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadatasImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadatasImpl.java new file mode 100644 index 0000000000000..49f8e09ba20b2 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadatasImpl.java @@ -0,0 +1,62 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyMetadatas; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyMetadata; +import com.microsoft.azure.management.policyinsights.v2019_10_01.SlimPolicyMetadata; + +class PolicyMetadatasImpl extends WrapperImpl implements PolicyMetadatas { + private final PolicyInsightsManager manager; + + PolicyMetadatasImpl(PolicyInsightsManager manager) { + super(manager.inner().policyMetadatas()); + this.manager = manager; + } + + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public Observable getResourceAsync(String resourceName) { + PolicyMetadatasInner client = this.inner(); + return client.getResourceAsync(resourceName) + .map(new Func1() { + @Override + public PolicyMetadata call(PolicyMetadataInner inner) { + return new PolicyMetadataImpl(inner, manager()); + } + }); + } + + @Override + public Observable listAsync() { + PolicyMetadatasInner client = this.inner(); + return client.listAsync() + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public SlimPolicyMetadata call(SlimPolicyMetadataInner inner) { + return new SlimPolicyMetadataImpl(inner, manager()); + } + }); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadatasInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadatasInner.java new file mode 100644 index 0000000000000..3a2cda207d5b9 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyMetadatasInner.java @@ -0,0 +1,470 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.policyinsights.v2019_10_01.ErrorResponseException; +import com.microsoft.azure.management.policyinsights.v2019_10_01.QueryOptions; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in PolicyMetadatas. + */ +public class PolicyMetadatasInner { + /** The Retrofit service to perform REST calls. */ + private PolicyMetadatasService service; + /** The service client containing this operation class. */ + private PolicyInsightsClientImpl client; + + /** + * Initializes an instance of PolicyMetadatasInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public PolicyMetadatasInner(Retrofit retrofit, PolicyInsightsClientImpl client) { + this.service = retrofit.create(PolicyMetadatasService.class); + this.client = client; + } + + /** + * The interface defining all the services for PolicyMetadatas to be + * used by Retrofit to perform actually REST calls. + */ + interface PolicyMetadatasService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyMetadatas getResource" }) + @GET("providers/Microsoft.PolicyInsights/policyMetadata/{resourceName}") + Observable> getResource(@Path(value = "resourceName", encoded = true) String resourceName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyMetadatas list" }) + @GET("providers/Microsoft.PolicyInsights/policyMetadata") + Observable> list(@Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyMetadatas listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Get policy metadata resource. + * + * @param resourceName The name of the policy metadata resource. + * @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 + * @return the PolicyMetadataInner object if successful. + */ + public PolicyMetadataInner getResource(String resourceName) { + return getResourceWithServiceResponseAsync(resourceName).toBlocking().single().body(); + } + + /** + * Get policy metadata resource. + * + * @param resourceName The name of the policy metadata resource. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getResourceAsync(String resourceName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getResourceWithServiceResponseAsync(resourceName), serviceCallback); + } + + /** + * Get policy metadata resource. + * + * @param resourceName The name of the policy metadata resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyMetadataInner object + */ + public Observable getResourceAsync(String resourceName) { + return getResourceWithServiceResponseAsync(resourceName).map(new Func1, PolicyMetadataInner>() { + @Override + public PolicyMetadataInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Get policy metadata resource. + * + * @param resourceName The name of the policy metadata resource. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyMetadataInner object + */ + public Observable> getResourceWithServiceResponseAsync(String resourceName) { + if (resourceName == null) { + throw new IllegalArgumentException("Parameter resourceName is required and cannot be null."); + } + final String apiVersion = "2019-10-01"; + return service.getResource(resourceName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getResourceDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Get a list of the policy metadata resources. + * + * @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 + * @return the PagedList<SlimPolicyMetadataInner> object if successful. + */ + public PagedList list() { + ServiceResponse> response = listSinglePageAsync().toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Get a list of the policy metadata resources. + * + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Get a list of the policy metadata resources. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SlimPolicyMetadataInner> object + */ + public Observable> listAsync() { + return listWithServiceResponseAsync() + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Get a list of the policy metadata resources. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SlimPolicyMetadataInner> object + */ + public Observable>> listWithServiceResponseAsync() { + return listSinglePageAsync() + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Get a list of the policy metadata resources. + * + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SlimPolicyMetadataInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync() { + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + return service.list(apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Get a list of the policy metadata resources. + * + * @param queryOptions Additional parameters for the operation + * @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 + * @return the PagedList<SlimPolicyMetadataInner> object if successful. + */ + public PagedList list(final QueryOptions queryOptions) { + ServiceResponse> response = listSinglePageAsync(queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Get a list of the policy metadata resources. + * + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Get a list of the policy metadata resources. + * + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SlimPolicyMetadataInner> object + */ + public Observable> listAsync(final QueryOptions queryOptions) { + return listWithServiceResponseAsync(queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Get a list of the policy metadata resources. + * + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SlimPolicyMetadataInner> object + */ + public Observable>> listWithServiceResponseAsync(final QueryOptions queryOptions) { + return listSinglePageAsync(queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Get a list of the policy metadata resources. + * + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SlimPolicyMetadataInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final QueryOptions queryOptions) { + Validator.validate(queryOptions); + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + return service.list(apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws ErrorResponseException, IOException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Get a list of the policy metadata resources. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @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 + * @return the PagedList<SlimPolicyMetadataInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Get a list of the policy metadata resources. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Get a list of the policy metadata resources. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SlimPolicyMetadataInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Get a list of the policy metadata resources. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<SlimPolicyMetadataInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Get a list of the policy metadata resources. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<SlimPolicyMetadataInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStateInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStateInner.java new file mode 100644 index 0000000000000..ccb6f3383dcd0 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStateInner.java @@ -0,0 +1,837 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import java.util.Map; +import org.joda.time.DateTime; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyEvaluationDetails; +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Policy state record. + */ +public class PolicyStateInner { + /** + * Unmatched properties from the message are deserialized this collection. + */ + @JsonProperty(value = "") + private Map additionalProperties; + + /** + * OData entity ID; always set to null since policy state records do not + * have an entity ID. + */ + @JsonProperty(value = "@odata\\.id") + private String odataid; + + /** + * OData context string; used by OData clients to resolve type information + * based on metadata. + */ + @JsonProperty(value = "@odata\\.context") + private String odatacontext; + + /** + * Timestamp for the policy state record. + */ + @JsonProperty(value = "timestamp") + private DateTime timestamp; + + /** + * Resource ID. + */ + @JsonProperty(value = "resourceId") + private String resourceId; + + /** + * Policy assignment ID. + */ + @JsonProperty(value = "policyAssignmentId") + private String policyAssignmentId; + + /** + * Policy definition ID. + */ + @JsonProperty(value = "policyDefinitionId") + private String policyDefinitionId; + + /** + * Effective parameters for the policy assignment. + */ + @JsonProperty(value = "effectiveParameters") + private String effectiveParameters; + + /** + * Flag which states whether the resource is compliant against the policy + * assignment it was evaluated against. This property is deprecated; please + * use ComplianceState instead. + */ + @JsonProperty(value = "isCompliant") + private Boolean isCompliant; + + /** + * Subscription ID. + */ + @JsonProperty(value = "subscriptionId") + private String subscriptionId; + + /** + * Resource type. + */ + @JsonProperty(value = "resourceType") + private String resourceType; + + /** + * Resource location. + */ + @JsonProperty(value = "resourceLocation") + private String resourceLocation; + + /** + * Resource group name. + */ + @JsonProperty(value = "resourceGroup") + private String resourceGroup; + + /** + * List of resource tags. + */ + @JsonProperty(value = "resourceTags") + private String resourceTags; + + /** + * Policy assignment name. + */ + @JsonProperty(value = "policyAssignmentName") + private String policyAssignmentName; + + /** + * Policy assignment owner. + */ + @JsonProperty(value = "policyAssignmentOwner") + private String policyAssignmentOwner; + + /** + * Policy assignment parameters. + */ + @JsonProperty(value = "policyAssignmentParameters") + private String policyAssignmentParameters; + + /** + * Policy assignment scope. + */ + @JsonProperty(value = "policyAssignmentScope") + private String policyAssignmentScope; + + /** + * Policy definition name. + */ + @JsonProperty(value = "policyDefinitionName") + private String policyDefinitionName; + + /** + * Policy definition action, i.e. effect. + */ + @JsonProperty(value = "policyDefinitionAction") + private String policyDefinitionAction; + + /** + * Policy definition category. + */ + @JsonProperty(value = "policyDefinitionCategory") + private String policyDefinitionCategory; + + /** + * Policy set definition ID, if the policy assignment is for a policy set. + */ + @JsonProperty(value = "policySetDefinitionId") + private String policySetDefinitionId; + + /** + * Policy set definition name, if the policy assignment is for a policy + * set. + */ + @JsonProperty(value = "policySetDefinitionName") + private String policySetDefinitionName; + + /** + * Policy set definition owner, if the policy assignment is for a policy + * set. + */ + @JsonProperty(value = "policySetDefinitionOwner") + private String policySetDefinitionOwner; + + /** + * Policy set definition category, if the policy assignment is for a policy + * set. + */ + @JsonProperty(value = "policySetDefinitionCategory") + private String policySetDefinitionCategory; + + /** + * Policy set definition parameters, if the policy assignment is for a + * policy set. + */ + @JsonProperty(value = "policySetDefinitionParameters") + private String policySetDefinitionParameters; + + /** + * Comma separated list of management group IDs, which represent the + * hierarchy of the management groups the resource is under. + */ + @JsonProperty(value = "managementGroupIds") + private String managementGroupIds; + + /** + * Reference ID for the policy definition inside the policy set, if the + * policy assignment is for a policy set. + */ + @JsonProperty(value = "policyDefinitionReferenceId") + private String policyDefinitionReferenceId; + + /** + * Compliance state of the resource. + */ + @JsonProperty(value = "complianceState") + private String complianceState; + + /** + * Policy evaluation details. + */ + @JsonProperty(value = "policyEvaluationDetails") + private PolicyEvaluationDetails policyEvaluationDetails; + + /** + * Policy definition group names. + */ + @JsonProperty(value = "policyDefinitionGroupNames") + private List policyDefinitionGroupNames; + + /** + * Get unmatched properties from the message are deserialized this collection. + * + * @return the additionalProperties value + */ + public Map additionalProperties() { + return this.additionalProperties; + } + + /** + * Set unmatched properties from the message are deserialized this collection. + * + * @param additionalProperties the additionalProperties value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withAdditionalProperties(Map additionalProperties) { + this.additionalProperties = additionalProperties; + return this; + } + + /** + * Get oData entity ID; always set to null since policy state records do not have an entity ID. + * + * @return the odataid value + */ + public String odataid() { + return this.odataid; + } + + /** + * Set oData entity ID; always set to null since policy state records do not have an entity ID. + * + * @param odataid the odataid value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withOdataid(String odataid) { + this.odataid = odataid; + return this; + } + + /** + * Get oData context string; used by OData clients to resolve type information based on metadata. + * + * @return the odatacontext value + */ + public String odatacontext() { + return this.odatacontext; + } + + /** + * Set oData context string; used by OData clients to resolve type information based on metadata. + * + * @param odatacontext the odatacontext value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withOdatacontext(String odatacontext) { + this.odatacontext = odatacontext; + return this; + } + + /** + * Get timestamp for the policy state record. + * + * @return the timestamp value + */ + public DateTime timestamp() { + return this.timestamp; + } + + /** + * Set timestamp for the policy state record. + * + * @param timestamp the timestamp value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withTimestamp(DateTime timestamp) { + this.timestamp = timestamp; + return this; + } + + /** + * Get resource ID. + * + * @return the resourceId value + */ + public String resourceId() { + return this.resourceId; + } + + /** + * Set resource ID. + * + * @param resourceId the resourceId value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withResourceId(String resourceId) { + this.resourceId = resourceId; + return this; + } + + /** + * Get policy assignment ID. + * + * @return the policyAssignmentId value + */ + public String policyAssignmentId() { + return this.policyAssignmentId; + } + + /** + * Set policy assignment ID. + * + * @param policyAssignmentId the policyAssignmentId value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyAssignmentId(String policyAssignmentId) { + this.policyAssignmentId = policyAssignmentId; + return this; + } + + /** + * Get policy definition ID. + * + * @return the policyDefinitionId value + */ + public String policyDefinitionId() { + return this.policyDefinitionId; + } + + /** + * Set policy definition ID. + * + * @param policyDefinitionId the policyDefinitionId value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyDefinitionId(String policyDefinitionId) { + this.policyDefinitionId = policyDefinitionId; + return this; + } + + /** + * Get effective parameters for the policy assignment. + * + * @return the effectiveParameters value + */ + public String effectiveParameters() { + return this.effectiveParameters; + } + + /** + * Set effective parameters for the policy assignment. + * + * @param effectiveParameters the effectiveParameters value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withEffectiveParameters(String effectiveParameters) { + this.effectiveParameters = effectiveParameters; + return this; + } + + /** + * Get flag which states whether the resource is compliant against the policy assignment it was evaluated against. This property is deprecated; please use ComplianceState instead. + * + * @return the isCompliant value + */ + public Boolean isCompliant() { + return this.isCompliant; + } + + /** + * Set flag which states whether the resource is compliant against the policy assignment it was evaluated against. This property is deprecated; please use ComplianceState instead. + * + * @param isCompliant the isCompliant value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withIsCompliant(Boolean isCompliant) { + this.isCompliant = isCompliant; + return this; + } + + /** + * Get subscription ID. + * + * @return the subscriptionId value + */ + public String subscriptionId() { + return this.subscriptionId; + } + + /** + * Set subscription ID. + * + * @param subscriptionId the subscriptionId value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withSubscriptionId(String subscriptionId) { + this.subscriptionId = subscriptionId; + return this; + } + + /** + * Get resource type. + * + * @return the resourceType value + */ + public String resourceType() { + return this.resourceType; + } + + /** + * Set resource type. + * + * @param resourceType the resourceType value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withResourceType(String resourceType) { + this.resourceType = resourceType; + return this; + } + + /** + * Get resource location. + * + * @return the resourceLocation value + */ + public String resourceLocation() { + return this.resourceLocation; + } + + /** + * Set resource location. + * + * @param resourceLocation the resourceLocation value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withResourceLocation(String resourceLocation) { + this.resourceLocation = resourceLocation; + return this; + } + + /** + * Get resource group name. + * + * @return the resourceGroup value + */ + public String resourceGroup() { + return this.resourceGroup; + } + + /** + * Set resource group name. + * + * @param resourceGroup the resourceGroup value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withResourceGroup(String resourceGroup) { + this.resourceGroup = resourceGroup; + return this; + } + + /** + * Get list of resource tags. + * + * @return the resourceTags value + */ + public String resourceTags() { + return this.resourceTags; + } + + /** + * Set list of resource tags. + * + * @param resourceTags the resourceTags value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withResourceTags(String resourceTags) { + this.resourceTags = resourceTags; + return this; + } + + /** + * Get policy assignment name. + * + * @return the policyAssignmentName value + */ + public String policyAssignmentName() { + return this.policyAssignmentName; + } + + /** + * Set policy assignment name. + * + * @param policyAssignmentName the policyAssignmentName value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyAssignmentName(String policyAssignmentName) { + this.policyAssignmentName = policyAssignmentName; + return this; + } + + /** + * Get policy assignment owner. + * + * @return the policyAssignmentOwner value + */ + public String policyAssignmentOwner() { + return this.policyAssignmentOwner; + } + + /** + * Set policy assignment owner. + * + * @param policyAssignmentOwner the policyAssignmentOwner value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyAssignmentOwner(String policyAssignmentOwner) { + this.policyAssignmentOwner = policyAssignmentOwner; + return this; + } + + /** + * Get policy assignment parameters. + * + * @return the policyAssignmentParameters value + */ + public String policyAssignmentParameters() { + return this.policyAssignmentParameters; + } + + /** + * Set policy assignment parameters. + * + * @param policyAssignmentParameters the policyAssignmentParameters value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyAssignmentParameters(String policyAssignmentParameters) { + this.policyAssignmentParameters = policyAssignmentParameters; + return this; + } + + /** + * Get policy assignment scope. + * + * @return the policyAssignmentScope value + */ + public String policyAssignmentScope() { + return this.policyAssignmentScope; + } + + /** + * Set policy assignment scope. + * + * @param policyAssignmentScope the policyAssignmentScope value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyAssignmentScope(String policyAssignmentScope) { + this.policyAssignmentScope = policyAssignmentScope; + return this; + } + + /** + * Get policy definition name. + * + * @return the policyDefinitionName value + */ + public String policyDefinitionName() { + return this.policyDefinitionName; + } + + /** + * Set policy definition name. + * + * @param policyDefinitionName the policyDefinitionName value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyDefinitionName(String policyDefinitionName) { + this.policyDefinitionName = policyDefinitionName; + return this; + } + + /** + * Get policy definition action, i.e. effect. + * + * @return the policyDefinitionAction value + */ + public String policyDefinitionAction() { + return this.policyDefinitionAction; + } + + /** + * Set policy definition action, i.e. effect. + * + * @param policyDefinitionAction the policyDefinitionAction value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyDefinitionAction(String policyDefinitionAction) { + this.policyDefinitionAction = policyDefinitionAction; + return this; + } + + /** + * Get policy definition category. + * + * @return the policyDefinitionCategory value + */ + public String policyDefinitionCategory() { + return this.policyDefinitionCategory; + } + + /** + * Set policy definition category. + * + * @param policyDefinitionCategory the policyDefinitionCategory value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyDefinitionCategory(String policyDefinitionCategory) { + this.policyDefinitionCategory = policyDefinitionCategory; + return this; + } + + /** + * Get policy set definition ID, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionId value + */ + public String policySetDefinitionId() { + return this.policySetDefinitionId; + } + + /** + * Set policy set definition ID, if the policy assignment is for a policy set. + * + * @param policySetDefinitionId the policySetDefinitionId value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicySetDefinitionId(String policySetDefinitionId) { + this.policySetDefinitionId = policySetDefinitionId; + return this; + } + + /** + * Get policy set definition name, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionName value + */ + public String policySetDefinitionName() { + return this.policySetDefinitionName; + } + + /** + * Set policy set definition name, if the policy assignment is for a policy set. + * + * @param policySetDefinitionName the policySetDefinitionName value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicySetDefinitionName(String policySetDefinitionName) { + this.policySetDefinitionName = policySetDefinitionName; + return this; + } + + /** + * Get policy set definition owner, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionOwner value + */ + public String policySetDefinitionOwner() { + return this.policySetDefinitionOwner; + } + + /** + * Set policy set definition owner, if the policy assignment is for a policy set. + * + * @param policySetDefinitionOwner the policySetDefinitionOwner value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicySetDefinitionOwner(String policySetDefinitionOwner) { + this.policySetDefinitionOwner = policySetDefinitionOwner; + return this; + } + + /** + * Get policy set definition category, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionCategory value + */ + public String policySetDefinitionCategory() { + return this.policySetDefinitionCategory; + } + + /** + * Set policy set definition category, if the policy assignment is for a policy set. + * + * @param policySetDefinitionCategory the policySetDefinitionCategory value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicySetDefinitionCategory(String policySetDefinitionCategory) { + this.policySetDefinitionCategory = policySetDefinitionCategory; + return this; + } + + /** + * Get policy set definition parameters, if the policy assignment is for a policy set. + * + * @return the policySetDefinitionParameters value + */ + public String policySetDefinitionParameters() { + return this.policySetDefinitionParameters; + } + + /** + * Set policy set definition parameters, if the policy assignment is for a policy set. + * + * @param policySetDefinitionParameters the policySetDefinitionParameters value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicySetDefinitionParameters(String policySetDefinitionParameters) { + this.policySetDefinitionParameters = policySetDefinitionParameters; + return this; + } + + /** + * Get comma separated list of management group IDs, which represent the hierarchy of the management groups the resource is under. + * + * @return the managementGroupIds value + */ + public String managementGroupIds() { + return this.managementGroupIds; + } + + /** + * Set comma separated list of management group IDs, which represent the hierarchy of the management groups the resource is under. + * + * @param managementGroupIds the managementGroupIds value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withManagementGroupIds(String managementGroupIds) { + this.managementGroupIds = managementGroupIds; + return this; + } + + /** + * Get reference ID for the policy definition inside the policy set, if the policy assignment is for a policy set. + * + * @return the policyDefinitionReferenceId value + */ + public String policyDefinitionReferenceId() { + return this.policyDefinitionReferenceId; + } + + /** + * Set reference ID for the policy definition inside the policy set, if the policy assignment is for a policy set. + * + * @param policyDefinitionReferenceId the policyDefinitionReferenceId value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyDefinitionReferenceId(String policyDefinitionReferenceId) { + this.policyDefinitionReferenceId = policyDefinitionReferenceId; + return this; + } + + /** + * Get compliance state of the resource. + * + * @return the complianceState value + */ + public String complianceState() { + return this.complianceState; + } + + /** + * Set compliance state of the resource. + * + * @param complianceState the complianceState value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withComplianceState(String complianceState) { + this.complianceState = complianceState; + return this; + } + + /** + * Get policy evaluation details. + * + * @return the policyEvaluationDetails value + */ + public PolicyEvaluationDetails policyEvaluationDetails() { + return this.policyEvaluationDetails; + } + + /** + * Set policy evaluation details. + * + * @param policyEvaluationDetails the policyEvaluationDetails value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyEvaluationDetails(PolicyEvaluationDetails policyEvaluationDetails) { + this.policyEvaluationDetails = policyEvaluationDetails; + return this; + } + + /** + * Get policy definition group names. + * + * @return the policyDefinitionGroupNames value + */ + public List policyDefinitionGroupNames() { + return this.policyDefinitionGroupNames; + } + + /** + * Set policy definition group names. + * + * @param policyDefinitionGroupNames the policyDefinitionGroupNames value to set + * @return the PolicyStateInner object itself. + */ + public PolicyStateInner withPolicyDefinitionGroupNames(List policyDefinitionGroupNames) { + this.policyDefinitionGroupNames = policyDefinitionGroupNames; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesImpl.java new file mode 100644 index 0000000000000..bf7a59f3ddb84 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesImpl.java @@ -0,0 +1,224 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStatesQueryResults; +import com.microsoft.azure.management.policyinsights.v2019_10_01.SummarizeResults; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStatesResource; + +class PolicyStatesImpl extends WrapperImpl implements PolicyStates { + private final PolicyInsightsManager manager; + + PolicyStatesImpl(PolicyInsightsManager manager) { + super(manager.inner().policyStates()); + this.manager = manager; + } + + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public Observable listQueryResultsForManagementGroupAsync(PolicyStatesResource policyStatesResource, String managementGroupName) { + PolicyStatesInner client = this.inner(); + return client.listQueryResultsForManagementGroupAsync(policyStatesResource, managementGroupName) + .map(new Func1() { + @Override + public PolicyStatesQueryResults call(PolicyStatesQueryResultsInner inner) { + return new PolicyStatesQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable summarizeForManagementGroupAsync(String managementGroupName) { + PolicyStatesInner client = this.inner(); + return client.summarizeForManagementGroupAsync(managementGroupName) + .map(new Func1() { + @Override + public SummarizeResults call(SummarizeResultsInner inner) { + return new SummarizeResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForSubscriptionAsync(PolicyStatesResource policyStatesResource, String subscriptionId) { + PolicyStatesInner client = this.inner(); + return client.listQueryResultsForSubscriptionAsync(policyStatesResource, subscriptionId) + .map(new Func1() { + @Override + public PolicyStatesQueryResults call(PolicyStatesQueryResultsInner inner) { + return new PolicyStatesQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable summarizeForSubscriptionAsync(String subscriptionId) { + PolicyStatesInner client = this.inner(); + return client.summarizeForSubscriptionAsync(subscriptionId) + .map(new Func1() { + @Override + public SummarizeResults call(SummarizeResultsInner inner) { + return new SummarizeResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForResourceGroupAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName) { + PolicyStatesInner client = this.inner(); + return client.listQueryResultsForResourceGroupAsync(policyStatesResource, subscriptionId, resourceGroupName) + .map(new Func1() { + @Override + public PolicyStatesQueryResults call(PolicyStatesQueryResultsInner inner) { + return new PolicyStatesQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable summarizeForResourceGroupAsync(String subscriptionId, String resourceGroupName) { + PolicyStatesInner client = this.inner(); + return client.summarizeForResourceGroupAsync(subscriptionId, resourceGroupName) + .map(new Func1() { + @Override + public SummarizeResults call(SummarizeResultsInner inner) { + return new SummarizeResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForResourceAsync(PolicyStatesResource policyStatesResource, String resourceId) { + PolicyStatesInner client = this.inner(); + return client.listQueryResultsForResourceAsync(policyStatesResource, resourceId) + .map(new Func1() { + @Override + public PolicyStatesQueryResults call(PolicyStatesQueryResultsInner inner) { + return new PolicyStatesQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable summarizeForResourceAsync(String resourceId) { + PolicyStatesInner client = this.inner(); + return client.summarizeForResourceAsync(resourceId) + .map(new Func1() { + @Override + public SummarizeResults call(SummarizeResultsInner inner) { + return new SummarizeResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForPolicySetDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName) { + PolicyStatesInner client = this.inner(); + return client.listQueryResultsForPolicySetDefinitionAsync(policyStatesResource, subscriptionId, policySetDefinitionName) + .map(new Func1() { + @Override + public PolicyStatesQueryResults call(PolicyStatesQueryResultsInner inner) { + return new PolicyStatesQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable summarizeForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName) { + PolicyStatesInner client = this.inner(); + return client.summarizeForPolicySetDefinitionAsync(subscriptionId, policySetDefinitionName) + .map(new Func1() { + @Override + public SummarizeResults call(SummarizeResultsInner inner) { + return new SummarizeResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForPolicyDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName) { + PolicyStatesInner client = this.inner(); + return client.listQueryResultsForPolicyDefinitionAsync(policyStatesResource, subscriptionId, policyDefinitionName) + .map(new Func1() { + @Override + public PolicyStatesQueryResults call(PolicyStatesQueryResultsInner inner) { + return new PolicyStatesQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable summarizeForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName) { + PolicyStatesInner client = this.inner(); + return client.summarizeForPolicyDefinitionAsync(subscriptionId, policyDefinitionName) + .map(new Func1() { + @Override + public SummarizeResults call(SummarizeResultsInner inner) { + return new SummarizeResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName) { + PolicyStatesInner client = this.inner(); + return client.listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(policyStatesResource, subscriptionId, policyAssignmentName) + .map(new Func1() { + @Override + public PolicyStatesQueryResults call(PolicyStatesQueryResultsInner inner) { + return new PolicyStatesQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable summarizeForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName) { + PolicyStatesInner client = this.inner(); + return client.summarizeForSubscriptionLevelPolicyAssignmentAsync(subscriptionId, policyAssignmentName) + .map(new Func1() { + @Override + public SummarizeResults call(SummarizeResultsInner inner) { + return new SummarizeResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName) { + PolicyStatesInner client = this.inner(); + return client.listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(policyStatesResource, subscriptionId, resourceGroupName, policyAssignmentName) + .map(new Func1() { + @Override + public PolicyStatesQueryResults call(PolicyStatesQueryResultsInner inner) { + return new PolicyStatesQueryResultsImpl(inner, manager()); + } + }); + } + + @Override + public Observable summarizeForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName) { + PolicyStatesInner client = this.inner(); + return client.summarizeForResourceGroupLevelPolicyAssignmentAsync(subscriptionId, resourceGroupName, policyAssignmentName) + .map(new Func1() { + @Override + public SummarizeResults call(SummarizeResultsInner inner) { + return new SummarizeResultsImpl(inner, manager()); + } + }); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesInner.java new file mode 100644 index 0000000000000..bc4c4cca0791e --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesInner.java @@ -0,0 +1,3237 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStatesResource; +import com.microsoft.azure.management.policyinsights.v2019_10_01.QueryFailureException; +import com.microsoft.azure.management.policyinsights.v2019_10_01.QueryOptions; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import okhttp3.ResponseBody; +import org.joda.time.DateTime; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.Query; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in PolicyStates. + */ +public class PolicyStatesInner { + /** The Retrofit service to perform REST calls. */ + private PolicyStatesService service; + /** The service client containing this operation class. */ + private PolicyInsightsClientImpl client; + + /** + * Initializes an instance of PolicyStatesInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public PolicyStatesInner(Retrofit retrofit, PolicyInsightsClientImpl client) { + this.service = retrofit.create(PolicyStatesService.class); + this.client = client; + } + + /** + * The interface defining all the services for PolicyStates to be + * used by Retrofit to perform actually REST calls. + */ + interface PolicyStatesService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates listQueryResultsForManagementGroup" }) + @POST("providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults") + Observable> listQueryResultsForManagementGroup(@Path("policyStatesResource") PolicyStatesResource policyStatesResource1, @Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupName") String managementGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates summarizeForManagementGroup" }) + @POST("providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize") + Observable> summarizeForManagementGroup(@Path("policyStatesSummaryResource") String policyStatesSummaryResource, @Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupName") String managementGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates listQueryResultsForSubscription" }) + @POST("subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults") + Observable> listQueryResultsForSubscription(@Path("policyStatesResource") PolicyStatesResource policyStatesResource1, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates summarizeForSubscription" }) + @POST("subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize") + Observable> summarizeForSubscription(@Path("policyStatesSummaryResource") String policyStatesSummaryResource, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates listQueryResultsForResourceGroup" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults") + Observable> listQueryResultsForResourceGroup(@Path("policyStatesResource") PolicyStatesResource policyStatesResource1, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates summarizeForResourceGroup" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize") + Observable> summarizeForResourceGroup(@Path("policyStatesSummaryResource") String policyStatesSummaryResource, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates listQueryResultsForResource" }) + @POST("{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults") + Observable> listQueryResultsForResource(@Path("policyStatesResource") PolicyStatesResource policyStatesResource1, @Path(value = "resourceId", encoded = true) String resourceId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Query("$expand") String expand, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates summarizeForResource" }) + @POST("{resourceId}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize") + Observable> summarizeForResource(@Path("policyStatesSummaryResource") String policyStatesSummaryResource, @Path(value = "resourceId", encoded = true) String resourceId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates listQueryResultsForPolicySetDefinition" }) + @POST("subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults") + Observable> listQueryResultsForPolicySetDefinition(@Path("policyStatesResource") PolicyStatesResource policyStatesResource1, @Path("subscriptionId") String subscriptionId, @Path("authorizationNamespace") String authorizationNamespace, @Path("policySetDefinitionName") String policySetDefinitionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates summarizeForPolicySetDefinition" }) + @POST("subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policySetDefinitions/{policySetDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize") + Observable> summarizeForPolicySetDefinition(@Path("policyStatesSummaryResource") String policyStatesSummaryResource, @Path("subscriptionId") String subscriptionId, @Path("authorizationNamespace") String authorizationNamespace, @Path("policySetDefinitionName") String policySetDefinitionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates listQueryResultsForPolicyDefinition" }) + @POST("subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults") + Observable> listQueryResultsForPolicyDefinition(@Path("policyStatesResource") PolicyStatesResource policyStatesResource1, @Path("subscriptionId") String subscriptionId, @Path("authorizationNamespace") String authorizationNamespace, @Path("policyDefinitionName") String policyDefinitionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates summarizeForPolicyDefinition" }) + @POST("subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyDefinitions/{policyDefinitionName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize") + Observable> summarizeForPolicyDefinition(@Path("policyStatesSummaryResource") String policyStatesSummaryResource, @Path("subscriptionId") String subscriptionId, @Path("authorizationNamespace") String authorizationNamespace, @Path("policyDefinitionName") String policyDefinitionName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates listQueryResultsForSubscriptionLevelPolicyAssignment" }) + @POST("subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults") + Observable> listQueryResultsForSubscriptionLevelPolicyAssignment(@Path("policyStatesResource") PolicyStatesResource policyStatesResource1, @Path("subscriptionId") String subscriptionId, @Path("authorizationNamespace") String authorizationNamespace, @Path("policyAssignmentName") String policyAssignmentName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates summarizeForSubscriptionLevelPolicyAssignment" }) + @POST("subscriptions/{subscriptionId}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize") + Observable> summarizeForSubscriptionLevelPolicyAssignment(@Path("policyStatesSummaryResource") String policyStatesSummaryResource, @Path("subscriptionId") String subscriptionId, @Path("authorizationNamespace") String authorizationNamespace, @Path("policyAssignmentName") String policyAssignmentName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates listQueryResultsForResourceGroupLevelPolicyAssignment" }) + @POST("subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesResource}/queryResults") + Observable> listQueryResultsForResourceGroupLevelPolicyAssignment(@Path("policyStatesResource") PolicyStatesResource policyStatesResource1, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("authorizationNamespace") String authorizationNamespace, @Path("policyAssignmentName") String policyAssignmentName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$orderby") String orderBy, @Query("$select") String select, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Query("$apply") String apply, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStates summarizeForResourceGroupLevelPolicyAssignment" }) + @POST("subscriptions/{subscriptionId}/resourcegroups/{resourceGroupName}/providers/{authorizationNamespace}/policyAssignments/{policyAssignmentName}/providers/Microsoft.PolicyInsights/policyStates/{policyStatesSummaryResource}/summarize") + Observable> summarizeForResourceGroupLevelPolicyAssignment(@Path("policyStatesSummaryResource") String policyStatesSummaryResource, @Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("authorizationNamespace") String authorizationNamespace, @Path("policyAssignmentName") String policyAssignmentName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$from") DateTime from, @Query("$to") DateTime to, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + } + + /** + * Queries policy states for the resources under the management group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForManagementGroup(PolicyStatesResource policyStatesResource, String managementGroupName) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(policyStatesResource, managementGroupName).toBlocking().single().body(); + } + + /** + * Queries policy states for the resources under the management group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param managementGroupName Management group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForManagementGroupAsync(PolicyStatesResource policyStatesResource, String managementGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForManagementGroupWithServiceResponseAsync(policyStatesResource, managementGroupName), serviceCallback); + } + + /** + * Queries policy states for the resources under the management group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForManagementGroupAsync(PolicyStatesResource policyStatesResource, String managementGroupName) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(policyStatesResource, managementGroupName).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resources under the management group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForManagementGroupWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String managementGroupName) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (managementGroupName == null) { + throw new IllegalArgumentException("Parameter managementGroupName is required and cannot be null."); + } + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForManagementGroup(policyStatesResource, managementGroupsNamespace, managementGroupName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy states for the resources under the management group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForManagementGroup(PolicyStatesResource policyStatesResource, String managementGroupName, QueryOptions queryOptions) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(policyStatesResource, managementGroupName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy states for the resources under the management group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForManagementGroupAsync(PolicyStatesResource policyStatesResource, String managementGroupName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForManagementGroupWithServiceResponseAsync(policyStatesResource, managementGroupName, queryOptions), serviceCallback); + } + + /** + * Queries policy states for the resources under the management group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForManagementGroupAsync(PolicyStatesResource policyStatesResource, String managementGroupName, QueryOptions queryOptions) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(policyStatesResource, managementGroupName, queryOptions).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resources under the management group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForManagementGroupWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String managementGroupName, QueryOptions queryOptions) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (managementGroupName == null) { + throw new IllegalArgumentException("Parameter managementGroupName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForManagementGroup(policyStatesResource, managementGroupsNamespace, managementGroupName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForManagementGroupDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Summarizes policy states for the resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForManagementGroup(String managementGroupName) { + return summarizeForManagementGroupWithServiceResponseAsync(managementGroupName).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForManagementGroupAsync(String managementGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForManagementGroupWithServiceResponseAsync(managementGroupName), serviceCallback); + } + + /** + * Summarizes policy states for the resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForManagementGroupAsync(String managementGroupName) { + return summarizeForManagementGroupWithServiceResponseAsync(managementGroupName).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForManagementGroupWithServiceResponseAsync(String managementGroupName) { + if (managementGroupName == null) { + throw new IllegalArgumentException("Parameter managementGroupName is required and cannot be null."); + } + final String policyStatesSummaryResource = "latest"; + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + DateTime from = null; + DateTime to = null; + String filter = null; + return service.summarizeForManagementGroup(policyStatesSummaryResource, managementGroupsNamespace, managementGroupName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Summarizes policy states for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForManagementGroup(String managementGroupName, QueryOptions queryOptions) { + return summarizeForManagementGroupWithServiceResponseAsync(managementGroupName, queryOptions).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForManagementGroupAsync(String managementGroupName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForManagementGroupWithServiceResponseAsync(managementGroupName, queryOptions), serviceCallback); + } + + /** + * Summarizes policy states for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForManagementGroupAsync(String managementGroupName, QueryOptions queryOptions) { + return summarizeForManagementGroupWithServiceResponseAsync(managementGroupName, queryOptions).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForManagementGroupWithServiceResponseAsync(String managementGroupName, QueryOptions queryOptions) { + if (managementGroupName == null) { + throw new IllegalArgumentException("Parameter managementGroupName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyStatesSummaryResource = "latest"; + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.summarizeForManagementGroup(policyStatesSummaryResource, managementGroupsNamespace, managementGroupName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse summarizeForManagementGroupDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy states for the resources under the subscription. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForSubscription(PolicyStatesResource policyStatesResource, String subscriptionId) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(policyStatesResource, subscriptionId).toBlocking().single().body(); + } + + /** + * Queries policy states for the resources under the subscription. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForSubscriptionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForSubscriptionWithServiceResponseAsync(policyStatesResource, subscriptionId), serviceCallback); + } + + /** + * Queries policy states for the resources under the subscription. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForSubscriptionAsync(PolicyStatesResource policyStatesResource, String subscriptionId) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(policyStatesResource, subscriptionId).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resources under the subscription. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForSubscriptionWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForSubscription(policyStatesResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy states for the resources under the subscription. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForSubscription(PolicyStatesResource policyStatesResource, String subscriptionId, QueryOptions queryOptions) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(policyStatesResource, subscriptionId, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy states for the resources under the subscription. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForSubscriptionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForSubscriptionWithServiceResponseAsync(policyStatesResource, subscriptionId, queryOptions), serviceCallback); + } + + /** + * Queries policy states for the resources under the subscription. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForSubscriptionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, QueryOptions queryOptions) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(policyStatesResource, subscriptionId, queryOptions).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resources under the subscription. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForSubscriptionWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, QueryOptions queryOptions) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForSubscription(policyStatesResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForSubscriptionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Summarizes policy states for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForSubscription(String subscriptionId) { + return summarizeForSubscriptionWithServiceResponseAsync(subscriptionId).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForSubscriptionAsync(String subscriptionId, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForSubscriptionWithServiceResponseAsync(subscriptionId), serviceCallback); + } + + /** + * Summarizes policy states for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForSubscriptionAsync(String subscriptionId) { + return summarizeForSubscriptionWithServiceResponseAsync(subscriptionId).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForSubscriptionWithServiceResponseAsync(String subscriptionId) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + final String policyStatesSummaryResource = "latest"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + DateTime from = null; + DateTime to = null; + String filter = null; + return service.summarizeForSubscription(policyStatesSummaryResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Summarizes policy states for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForSubscription(String subscriptionId, QueryOptions queryOptions) { + return summarizeForSubscriptionWithServiceResponseAsync(subscriptionId, queryOptions).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForSubscriptionAsync(String subscriptionId, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForSubscriptionWithServiceResponseAsync(subscriptionId, queryOptions), serviceCallback); + } + + /** + * Summarizes policy states for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForSubscriptionAsync(String subscriptionId, QueryOptions queryOptions) { + return summarizeForSubscriptionWithServiceResponseAsync(subscriptionId, queryOptions).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForSubscriptionWithServiceResponseAsync(String subscriptionId, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyStatesSummaryResource = "latest"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.summarizeForSubscription(policyStatesSummaryResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse summarizeForSubscriptionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy states for the resources under the resource group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForResourceGroup(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName).toBlocking().single().body(); + } + + /** + * Queries policy states for the resources under the resource group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceGroupAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceGroupWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName), serviceCallback); + } + + /** + * Queries policy states for the resources under the resource group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForResourceGroupAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resources under the resource group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForResourceGroupWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForResourceGroup(policyStatesResource, subscriptionId, resourceGroupName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy states for the resources under the resource group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForResourceGroup(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, QueryOptions queryOptions) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy states for the resources under the resource group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceGroupAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceGroupWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, queryOptions), serviceCallback); + } + + /** + * Queries policy states for the resources under the resource group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForResourceGroupAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, QueryOptions queryOptions) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, queryOptions).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resources under the resource group. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForResourceGroupWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, QueryOptions queryOptions) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForResourceGroup(policyStatesResource, subscriptionId, resourceGroupName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForResourceGroupDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Summarizes policy states for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForResourceGroup(String subscriptionId, String resourceGroupName) { + return summarizeForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForResourceGroupAsync(String subscriptionId, String resourceGroupName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName), serviceCallback); + } + + /** + * Summarizes policy states for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForResourceGroupAsync(String subscriptionId, String resourceGroupName) { + return summarizeForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForResourceGroupWithServiceResponseAsync(String subscriptionId, String resourceGroupName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + final String policyStatesSummaryResource = "latest"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + DateTime from = null; + DateTime to = null; + String filter = null; + return service.summarizeForResourceGroup(policyStatesSummaryResource, subscriptionId, resourceGroupName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Summarizes policy states for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForResourceGroup(String subscriptionId, String resourceGroupName, QueryOptions queryOptions) { + return summarizeForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, queryOptions).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForResourceGroupAsync(String subscriptionId, String resourceGroupName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, queryOptions), serviceCallback); + } + + /** + * Summarizes policy states for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForResourceGroupAsync(String subscriptionId, String resourceGroupName, QueryOptions queryOptions) { + return summarizeForResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, queryOptions).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resources under the resource group. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForResourceGroupWithServiceResponseAsync(String subscriptionId, String resourceGroupName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyStatesSummaryResource = "latest"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.summarizeForResourceGroup(policyStatesSummaryResource, subscriptionId, resourceGroupName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse summarizeForResourceGroupDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy states for the resource. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForResource(PolicyStatesResource policyStatesResource, String resourceId) { + return listQueryResultsForResourceWithServiceResponseAsync(policyStatesResource, resourceId).toBlocking().single().body(); + } + + /** + * Queries policy states for the resource. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param resourceId Resource ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceAsync(PolicyStatesResource policyStatesResource, String resourceId, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceWithServiceResponseAsync(policyStatesResource, resourceId), serviceCallback); + } + + /** + * Queries policy states for the resource. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForResourceAsync(PolicyStatesResource policyStatesResource, String resourceId) { + return listQueryResultsForResourceWithServiceResponseAsync(policyStatesResource, resourceId).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resource. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForResourceWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String resourceId) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + String expand = null; + return service.listQueryResultsForResource(policyStatesResource, resourceId, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, expand, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy states for the resource. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForResource(PolicyStatesResource policyStatesResource, String resourceId, QueryOptions queryOptions) { + return listQueryResultsForResourceWithServiceResponseAsync(policyStatesResource, resourceId, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy states for the resource. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceAsync(PolicyStatesResource policyStatesResource, String resourceId, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceWithServiceResponseAsync(policyStatesResource, resourceId, queryOptions), serviceCallback); + } + + /** + * Queries policy states for the resource. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForResourceAsync(PolicyStatesResource policyStatesResource, String resourceId, QueryOptions queryOptions) { + return listQueryResultsForResourceWithServiceResponseAsync(policyStatesResource, resourceId, queryOptions).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resource. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForResourceWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String resourceId, QueryOptions queryOptions) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + String expand = null; + if (queryOptions != null) { + expand = queryOptions.expand(); + } + return service.listQueryResultsForResource(policyStatesResource, resourceId, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, expand, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForResourceDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Summarizes policy states for the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForResource(String resourceId) { + return summarizeForResourceWithServiceResponseAsync(resourceId).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resource. + * + * @param resourceId Resource ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForResourceAsync(String resourceId, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForResourceWithServiceResponseAsync(resourceId), serviceCallback); + } + + /** + * Summarizes policy states for the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForResourceAsync(String resourceId) { + return summarizeForResourceWithServiceResponseAsync(resourceId).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForResourceWithServiceResponseAsync(String resourceId) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + final String policyStatesSummaryResource = "latest"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + DateTime from = null; + DateTime to = null; + String filter = null; + return service.summarizeForResource(policyStatesSummaryResource, resourceId, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Summarizes policy states for the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForResource(String resourceId, QueryOptions queryOptions) { + return summarizeForResourceWithServiceResponseAsync(resourceId, queryOptions).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForResourceAsync(String resourceId, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForResourceWithServiceResponseAsync(resourceId, queryOptions), serviceCallback); + } + + /** + * Summarizes policy states for the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForResourceAsync(String resourceId, QueryOptions queryOptions) { + return summarizeForResourceWithServiceResponseAsync(resourceId, queryOptions).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForResourceWithServiceResponseAsync(String resourceId, QueryOptions queryOptions) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyStatesSummaryResource = "latest"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.summarizeForResource(policyStatesSummaryResource, resourceId, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse summarizeForResourceDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy states for the subscription level policy set definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForPolicySetDefinition(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName) { + return listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policySetDefinitionName).toBlocking().single().body(); + } + + /** + * Queries policy states for the subscription level policy set definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForPolicySetDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policySetDefinitionName), serviceCallback); + } + + /** + * Queries policy states for the subscription level policy set definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForPolicySetDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName) { + return listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policySetDefinitionName).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the subscription level policy set definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policySetDefinitionName == null) { + throw new IllegalArgumentException("Parameter policySetDefinitionName is required and cannot be null."); + } + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForPolicySetDefinition(policyStatesResource, subscriptionId, authorizationNamespace, policySetDefinitionName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForPolicySetDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy states for the subscription level policy set definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForPolicySetDefinition(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions) { + return listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policySetDefinitionName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy states for the subscription level policy set definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForPolicySetDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policySetDefinitionName, queryOptions), serviceCallback); + } + + /** + * Queries policy states for the subscription level policy set definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForPolicySetDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions) { + return listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policySetDefinitionName, queryOptions).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the subscription level policy set definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForPolicySetDefinitionWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policySetDefinitionName == null) { + throw new IllegalArgumentException("Parameter policySetDefinitionName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForPolicySetDefinition(policyStatesResource, subscriptionId, authorizationNamespace, policySetDefinitionName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForPolicySetDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForPolicySetDefinitionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Summarizes policy states for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForPolicySetDefinition(String subscriptionId, String policySetDefinitionName) { + return summarizeForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName), serviceCallback); + } + + /** + * Summarizes policy states for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName) { + return summarizeForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForPolicySetDefinitionWithServiceResponseAsync(String subscriptionId, String policySetDefinitionName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policySetDefinitionName == null) { + throw new IllegalArgumentException("Parameter policySetDefinitionName is required and cannot be null."); + } + final String policyStatesSummaryResource = "latest"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + DateTime from = null; + DateTime to = null; + String filter = null; + return service.summarizeForPolicySetDefinition(policyStatesSummaryResource, subscriptionId, authorizationNamespace, policySetDefinitionName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForPolicySetDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Summarizes policy states for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForPolicySetDefinition(String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions) { + return summarizeForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName, queryOptions).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName, queryOptions), serviceCallback); + } + + /** + * Summarizes policy states for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForPolicySetDefinitionAsync(String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions) { + return summarizeForPolicySetDefinitionWithServiceResponseAsync(subscriptionId, policySetDefinitionName, queryOptions).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the subscription level policy set definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policySetDefinitionName Policy set definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForPolicySetDefinitionWithServiceResponseAsync(String subscriptionId, String policySetDefinitionName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policySetDefinitionName == null) { + throw new IllegalArgumentException("Parameter policySetDefinitionName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyStatesSummaryResource = "latest"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.summarizeForPolicySetDefinition(policyStatesSummaryResource, subscriptionId, authorizationNamespace, policySetDefinitionName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForPolicySetDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse summarizeForPolicySetDefinitionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy states for the subscription level policy definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForPolicyDefinition(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName) { + return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policyDefinitionName).toBlocking().single().body(); + } + + /** + * Queries policy states for the subscription level policy definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForPolicyDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForPolicyDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policyDefinitionName), serviceCallback); + } + + /** + * Queries policy states for the subscription level policy definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForPolicyDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName) { + return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policyDefinitionName).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the subscription level policy definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForPolicyDefinitionWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyDefinitionName == null) { + throw new IllegalArgumentException("Parameter policyDefinitionName is required and cannot be null."); + } + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForPolicyDefinition(policyStatesResource, subscriptionId, authorizationNamespace, policyDefinitionName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForPolicyDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy states for the subscription level policy definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForPolicyDefinition(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { + return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policyDefinitionName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy states for the subscription level policy definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForPolicyDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForPolicyDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policyDefinitionName, queryOptions), serviceCallback); + } + + /** + * Queries policy states for the subscription level policy definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForPolicyDefinitionAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { + return listQueryResultsForPolicyDefinitionWithServiceResponseAsync(policyStatesResource, subscriptionId, policyDefinitionName, queryOptions).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the subscription level policy definition. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForPolicyDefinitionWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyDefinitionName == null) { + throw new IllegalArgumentException("Parameter policyDefinitionName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForPolicyDefinition(policyStatesResource, subscriptionId, authorizationNamespace, policyDefinitionName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForPolicyDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForPolicyDefinitionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Summarizes policy states for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForPolicyDefinition(String subscriptionId, String policyDefinitionName) { + return summarizeForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName), serviceCallback); + } + + /** + * Summarizes policy states for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName) { + return summarizeForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForPolicyDefinitionWithServiceResponseAsync(String subscriptionId, String policyDefinitionName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyDefinitionName == null) { + throw new IllegalArgumentException("Parameter policyDefinitionName is required and cannot be null."); + } + final String policyStatesSummaryResource = "latest"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + DateTime from = null; + DateTime to = null; + String filter = null; + return service.summarizeForPolicyDefinition(policyStatesSummaryResource, subscriptionId, authorizationNamespace, policyDefinitionName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForPolicyDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Summarizes policy states for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForPolicyDefinition(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { + return summarizeForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions), serviceCallback); + } + + /** + * Summarizes policy states for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForPolicyDefinitionAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { + return summarizeForPolicyDefinitionWithServiceResponseAsync(subscriptionId, policyDefinitionName, queryOptions).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the subscription level policy definition. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyDefinitionName Policy definition name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForPolicyDefinitionWithServiceResponseAsync(String subscriptionId, String policyDefinitionName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyDefinitionName == null) { + throw new IllegalArgumentException("Parameter policyDefinitionName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyStatesSummaryResource = "latest"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.summarizeForPolicyDefinition(policyStatesSummaryResource, subscriptionId, authorizationNamespace, policyDefinitionName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForPolicyDefinitionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse summarizeForPolicyDefinitionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy states for the subscription level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForSubscriptionLevelPolicyAssignment(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName) { + return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, policyAssignmentName).toBlocking().single().body(); + } + + /** + * Queries policy states for the subscription level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, policyAssignmentName), serviceCallback); + } + + /** + * Queries policy states for the subscription level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName) { + return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, policyAssignmentName).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the subscription level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForSubscriptionLevelPolicyAssignment(policyStatesResource, subscriptionId, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForSubscriptionLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy states for the subscription level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForSubscriptionLevelPolicyAssignment(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) { + return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, policyAssignmentName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy states for the subscription level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, policyAssignmentName, queryOptions), serviceCallback); + } + + /** + * Queries policy states for the subscription level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForSubscriptionLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) { + return listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, policyAssignmentName, queryOptions).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the subscription level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForSubscriptionLevelPolicyAssignment(policyStatesResource, subscriptionId, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForSubscriptionLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForSubscriptionLevelPolicyAssignmentDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Summarizes policy states for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForSubscriptionLevelPolicyAssignment(String subscriptionId, String policyAssignmentName) { + return summarizeForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName), serviceCallback); + } + + /** + * Summarizes policy states for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName) { + return summarizeForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(String subscriptionId, String policyAssignmentName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + final String policyStatesSummaryResource = "latest"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + DateTime from = null; + DateTime to = null; + String filter = null; + return service.summarizeForSubscriptionLevelPolicyAssignment(policyStatesSummaryResource, subscriptionId, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForSubscriptionLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Summarizes policy states for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForSubscriptionLevelPolicyAssignment(String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) { + return summarizeForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName, queryOptions).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName, queryOptions), serviceCallback); + } + + /** + * Summarizes policy states for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForSubscriptionLevelPolicyAssignmentAsync(String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) { + return summarizeForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, policyAssignmentName, queryOptions).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the subscription level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForSubscriptionLevelPolicyAssignmentWithServiceResponseAsync(String subscriptionId, String policyAssignmentName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyStatesSummaryResource = "latest"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.summarizeForSubscriptionLevelPolicyAssignment(policyStatesSummaryResource, subscriptionId, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForSubscriptionLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse summarizeForSubscriptionLevelPolicyAssignmentDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy states for the resource group level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForResourceGroupLevelPolicyAssignment(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName) { + return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, policyAssignmentName).toBlocking().single().body(); + } + + /** + * Queries policy states for the resource group level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, policyAssignmentName), serviceCallback); + } + + /** + * Queries policy states for the resource group level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName) { + return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, policyAssignmentName).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resource group level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String orderBy = null; + String select = null; + DateTime from = null; + DateTime to = null; + String filter = null; + String apply = null; + return service.listQueryResultsForResourceGroupLevelPolicyAssignment(policyStatesResource, subscriptionId, resourceGroupName, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceGroupLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy states for the resource group level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PolicyStatesQueryResultsInner object if successful. + */ + public PolicyStatesQueryResultsInner listQueryResultsForResourceGroupLevelPolicyAssignment(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) { + return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, policyAssignmentName, queryOptions).toBlocking().single().body(); + } + + /** + * Queries policy states for the resource group level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, policyAssignmentName, queryOptions), serviceCallback); + } + + /** + * Queries policy states for the resource group level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable listQueryResultsForResourceGroupLevelPolicyAssignmentAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) { + return listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(policyStatesResource, subscriptionId, resourceGroupName, policyAssignmentName, queryOptions).map(new Func1, PolicyStatesQueryResultsInner>() { + @Override + public PolicyStatesQueryResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Queries policy states for the resource group level policy assignment. + * + * @param policyStatesResource The virtual resource under PolicyStates resource type. In a given time range, 'latest' represents the latest policy state(s), whereas 'default' represents all policy state(s). Possible values include: 'default', 'latest' + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PolicyStatesQueryResultsInner object + */ + public Observable> listQueryResultsForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(PolicyStatesResource policyStatesResource, String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) { + if (policyStatesResource == null) { + throw new IllegalArgumentException("Parameter policyStatesResource is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String orderBy = null; + if (queryOptions != null) { + orderBy = queryOptions.orderBy(); + } + String select = null; + if (queryOptions != null) { + select = queryOptions.select(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + String apply = null; + if (queryOptions != null) { + apply = queryOptions.apply(); + } + return service.listQueryResultsForResourceGroupLevelPolicyAssignment(policyStatesResource, subscriptionId, resourceGroupName, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, orderBy, select, from, to, filter, apply, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = listQueryResultsForResourceGroupLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse listQueryResultsForResourceGroupLevelPolicyAssignmentDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Summarizes policy states for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForResourceGroupLevelPolicyAssignment(String subscriptionId, String resourceGroupName, String policyAssignmentName) { + return summarizeForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName), serviceCallback); + } + + /** + * Summarizes policy states for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName) { + return summarizeForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + final String policyStatesSummaryResource = "latest"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + final QueryOptions queryOptions = null; + Integer top = null; + DateTime from = null; + DateTime to = null; + String filter = null; + return service.summarizeForResourceGroupLevelPolicyAssignment(policyStatesSummaryResource, subscriptionId, resourceGroupName, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForResourceGroupLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Summarizes policy states for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the SummarizeResultsInner object if successful. + */ + public SummarizeResultsInner summarizeForResourceGroupLevelPolicyAssignment(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) { + return summarizeForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName, queryOptions).toBlocking().single().body(); + } + + /** + * Summarizes policy states for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture summarizeForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(summarizeForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName, queryOptions), serviceCallback); + } + + /** + * Summarizes policy states for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable summarizeForResourceGroupLevelPolicyAssignmentAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) { + return summarizeForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(subscriptionId, resourceGroupName, policyAssignmentName, queryOptions).map(new Func1, SummarizeResultsInner>() { + @Override + public SummarizeResultsInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Summarizes policy states for the resource group level policy assignment. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param policyAssignmentName Policy assignment name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the SummarizeResultsInner object + */ + public Observable> summarizeForResourceGroupLevelPolicyAssignmentWithServiceResponseAsync(String subscriptionId, String resourceGroupName, String policyAssignmentName, QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (policyAssignmentName == null) { + throw new IllegalArgumentException("Parameter policyAssignmentName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyStatesSummaryResource = "latest"; + final String authorizationNamespace = "Microsoft.Authorization"; + final String apiVersion = "2019-10-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + DateTime from = null; + if (queryOptions != null) { + from = queryOptions.from(); + } + DateTime to = null; + if (queryOptions != null) { + to = queryOptions.to(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.summarizeForResourceGroupLevelPolicyAssignment(policyStatesSummaryResource, subscriptionId, resourceGroupName, authorizationNamespace, policyAssignmentName, apiVersion, this.client.acceptLanguage(), top, from, to, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = summarizeForResourceGroupLevelPolicyAssignmentDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse summarizeForResourceGroupLevelPolicyAssignmentDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesQueryResultsImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesQueryResultsImpl.java new file mode 100644 index 0000000000000..e11f9be526bb4 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesQueryResultsImpl.java @@ -0,0 +1,42 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyStatesQueryResults; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import java.util.List; + +class PolicyStatesQueryResultsImpl extends WrapperImpl implements PolicyStatesQueryResults { + private final PolicyInsightsManager manager; + PolicyStatesQueryResultsImpl(PolicyStatesQueryResultsInner inner, PolicyInsightsManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public String odatacontext() { + return this.inner().odatacontext(); + } + + @Override + public Integer odatacount() { + return this.inner().odatacount(); + } + + @Override + public List value() { + return this.inner().value(); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesQueryResultsInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesQueryResultsInner.java new file mode 100644 index 0000000000000..2dbcf397ab41e --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyStatesQueryResultsInner.java @@ -0,0 +1,98 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import java.util.List; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Query results. + */ +public class PolicyStatesQueryResultsInner { + /** + * OData context string; used by OData clients to resolve type information + * based on metadata. + */ + @JsonProperty(value = "@odata\\.context") + private String odatacontext; + + /** + * OData entity count; represents the number of policy state records + * returned. + */ + @JsonProperty(value = "@odata\\.count") + private Integer odatacount; + + /** + * Query results. + */ + @JsonProperty(value = "value") + private List value; + + /** + * Get oData context string; used by OData clients to resolve type information based on metadata. + * + * @return the odatacontext value + */ + public String odatacontext() { + return this.odatacontext; + } + + /** + * Set oData context string; used by OData clients to resolve type information based on metadata. + * + * @param odatacontext the odatacontext value to set + * @return the PolicyStatesQueryResultsInner object itself. + */ + public PolicyStatesQueryResultsInner withOdatacontext(String odatacontext) { + this.odatacontext = odatacontext; + return this; + } + + /** + * Get oData entity count; represents the number of policy state records returned. + * + * @return the odatacount value + */ + public Integer odatacount() { + return this.odatacount; + } + + /** + * Set oData entity count; represents the number of policy state records returned. + * + * @param odatacount the odatacount value to set + * @return the PolicyStatesQueryResultsInner object itself. + */ + public PolicyStatesQueryResultsInner withOdatacount(Integer odatacount) { + this.odatacount = odatacount; + return this; + } + + /** + * Get query results. + * + * @return the value value + */ + public List value() { + return this.value; + } + + /** + * Set query results. + * + * @param value the value value to set + * @return the PolicyStatesQueryResultsInner object itself. + */ + public PolicyStatesQueryResultsInner withValue(List value) { + this.value = value; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourceImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourceImpl.java new file mode 100644 index 0000000000000..26f2ee6851e49 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourceImpl.java @@ -0,0 +1,54 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResource; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.policyinsights.v2019_10_01.TrackedResourceModificationDetails; +import org.joda.time.DateTime; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyDetails; + +class PolicyTrackedResourceImpl extends WrapperImpl implements PolicyTrackedResource { + private final PolicyInsightsManager manager; + PolicyTrackedResourceImpl(PolicyTrackedResourceInner inner, PolicyInsightsManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public TrackedResourceModificationDetails createdBy() { + return this.inner().createdBy(); + } + + @Override + public TrackedResourceModificationDetails lastModifiedBy() { + return this.inner().lastModifiedBy(); + } + + @Override + public DateTime lastUpdateUtc() { + return this.inner().lastUpdateUtc(); + } + + @Override + public PolicyDetails policyDetails() { + return this.inner().policyDetails(); + } + + @Override + public String trackedResourceId() { + return this.inner().trackedResourceId(); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourceInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourceInner.java new file mode 100644 index 0000000000000..96ef639474496 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourceInner.java @@ -0,0 +1,97 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyDetails; +import com.microsoft.azure.management.policyinsights.v2019_10_01.TrackedResourceModificationDetails; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Policy tracked resource record. + */ +public class PolicyTrackedResourceInner { + /** + * The ID of the policy tracked resource. + */ + @JsonProperty(value = "trackedResourceId", access = JsonProperty.Access.WRITE_ONLY) + private String trackedResourceId; + + /** + * The details of the policy that require the tracked resource. + */ + @JsonProperty(value = "policyDetails", access = JsonProperty.Access.WRITE_ONLY) + private PolicyDetails policyDetails; + + /** + * The details of the policy triggered deployment that created the tracked + * resource. + */ + @JsonProperty(value = "createdBy", access = JsonProperty.Access.WRITE_ONLY) + private TrackedResourceModificationDetails createdBy; + + /** + * The details of the policy triggered deployment that modified the tracked + * resource. + */ + @JsonProperty(value = "lastModifiedBy", access = JsonProperty.Access.WRITE_ONLY) + private TrackedResourceModificationDetails lastModifiedBy; + + /** + * Timestamp of the last update to the tracked resource. + */ + @JsonProperty(value = "lastUpdateUtc", access = JsonProperty.Access.WRITE_ONLY) + private DateTime lastUpdateUtc; + + /** + * Get the ID of the policy tracked resource. + * + * @return the trackedResourceId value + */ + public String trackedResourceId() { + return this.trackedResourceId; + } + + /** + * Get the details of the policy that require the tracked resource. + * + * @return the policyDetails value + */ + public PolicyDetails policyDetails() { + return this.policyDetails; + } + + /** + * Get the details of the policy triggered deployment that created the tracked resource. + * + * @return the createdBy value + */ + public TrackedResourceModificationDetails createdBy() { + return this.createdBy; + } + + /** + * Get the details of the policy triggered deployment that modified the tracked resource. + * + * @return the lastModifiedBy value + */ + public TrackedResourceModificationDetails lastModifiedBy() { + return this.lastModifiedBy; + } + + /** + * Get timestamp of the last update to the tracked resource. + * + * @return the lastUpdateUtc value + */ + public DateTime lastUpdateUtc() { + return this.lastUpdateUtc; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourcesImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourcesImpl.java new file mode 100644 index 0000000000000..0025b0f21c98d --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourcesImpl.java @@ -0,0 +1,103 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * abc + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResource; + +class PolicyTrackedResourcesImpl extends WrapperImpl implements PolicyTrackedResources { + private final PolicyInsightsManager manager; + + PolicyTrackedResourcesImpl(PolicyInsightsManager manager) { + super(manager.inner().policyTrackedResources()); + this.manager = manager; + } + + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public Observable listQueryResultsForManagementGroupAsync(final String managementGroupName) { + PolicyTrackedResourcesInner client = this.inner(); + return client.listQueryResultsForManagementGroupAsync(managementGroupName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public PolicyTrackedResource call(PolicyTrackedResourceInner inner) { + return new PolicyTrackedResourceImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForSubscriptionAsync(final String subscriptionId) { + PolicyTrackedResourcesInner client = this.inner(); + return client.listQueryResultsForSubscriptionAsync(subscriptionId) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public PolicyTrackedResource call(PolicyTrackedResourceInner inner) { + return new PolicyTrackedResourceImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForResourceGroupAsync(final String resourceGroupName, final String subscriptionId) { + PolicyTrackedResourcesInner client = this.inner(); + return client.listQueryResultsForResourceGroupAsync(resourceGroupName, subscriptionId) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public PolicyTrackedResource call(PolicyTrackedResourceInner inner) { + return new PolicyTrackedResourceImpl(inner, manager()); + } + }); + } + + @Override + public Observable listQueryResultsForResourceAsync(final String resourceId) { + PolicyTrackedResourcesInner client = this.inner(); + return client.listQueryResultsForResourceAsync(resourceId) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public PolicyTrackedResource call(PolicyTrackedResourceInner inner) { + return new PolicyTrackedResourceImpl(inner, manager()); + } + }); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourcesInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourcesInner.java new file mode 100644 index 0000000000000..a5f76d14b6472 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/PolicyTrackedResourcesInner.java @@ -0,0 +1,1486 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.policyinsights.v2019_10_01.QueryFailureException; +import com.microsoft.azure.management.policyinsights.v2019_10_01.QueryOptions; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in PolicyTrackedResources. + */ +public class PolicyTrackedResourcesInner { + /** The Retrofit service to perform REST calls. */ + private PolicyTrackedResourcesService service; + /** The service client containing this operation class. */ + private PolicyInsightsClientImpl client; + + /** + * Initializes an instance of PolicyTrackedResourcesInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public PolicyTrackedResourcesInner(Retrofit retrofit, PolicyInsightsClientImpl client) { + this.service = retrofit.create(PolicyTrackedResourcesService.class); + this.client = client; + } + + /** + * The interface defining all the services for PolicyTrackedResources to be + * used by Retrofit to perform actually REST calls. + */ + interface PolicyTrackedResourcesService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources listQueryResultsForManagementGroup" }) + @POST("providers/{managementGroupsNamespace}/managementGroups/{managementGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults") + Observable> listQueryResultsForManagementGroup(@Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupName") String managementGroupName, @Path("policyTrackedResourcesResource") String policyTrackedResourcesResource, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources listQueryResultsForSubscription" }) + @POST("subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults") + Observable> listQueryResultsForSubscription(@Path("policyTrackedResourcesResource") String policyTrackedResourcesResource, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources listQueryResultsForResourceGroup" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults") + Observable> listQueryResultsForResourceGroup(@Path("resourceGroupName") String resourceGroupName, @Path("policyTrackedResourcesResource") String policyTrackedResourcesResource, @Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources listQueryResultsForResource" }) + @POST("{resourceId}/providers/Microsoft.PolicyInsights/policyTrackedResources/{policyTrackedResourcesResource}/queryResults") + Observable> listQueryResultsForResource(@Path(value = "resourceId", encoded = true) String resourceId, @Path("policyTrackedResourcesResource") String policyTrackedResourcesResource, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources listQueryResultsForManagementGroupNext" }) + @GET + Observable> listQueryResultsForManagementGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources listQueryResultsForSubscriptionNext" }) + @GET + Observable> listQueryResultsForSubscriptionNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources listQueryResultsForResourceGroupNext" }) + @GET + Observable> listQueryResultsForResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.PolicyTrackedResources listQueryResultsForResourceNext" }) + @GET + Observable> listQueryResultsForResourceNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForManagementGroup(final String managementGroupName) { + ServiceResponse> response = listQueryResultsForManagementGroupSinglePageAsync(managementGroupName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForManagementGroupAsync(final String managementGroupName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForManagementGroupSinglePageAsync(managementGroupName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForManagementGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForManagementGroupAsync(final String managementGroupName) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(managementGroupName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForManagementGroupWithServiceResponseAsync(final String managementGroupName) { + return listQueryResultsForManagementGroupSinglePageAsync(managementGroupName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForManagementGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForManagementGroupSinglePageAsync(final String managementGroupName) { + if (managementGroupName == null) { + throw new IllegalArgumentException("Parameter managementGroupName is required and cannot be null."); + } + final String managementGroupsNamespace = "Microsoft.Management"; + final String policyTrackedResourcesResource = "default"; + final String apiVersion = "2018-07-01-preview"; + final QueryOptions queryOptions = null; + Integer top = null; + String filter = null; + return service.listQueryResultsForManagementGroup(managementGroupsNamespace, managementGroupName, policyTrackedResourcesResource, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForManagementGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForManagementGroup(final String managementGroupName, final QueryOptions queryOptions) { + ServiceResponse> response = listQueryResultsForManagementGroupSinglePageAsync(managementGroupName, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForManagementGroupAsync(final String managementGroupName, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForManagementGroupSinglePageAsync(managementGroupName, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForManagementGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForManagementGroupAsync(final String managementGroupName, final QueryOptions queryOptions) { + return listQueryResultsForManagementGroupWithServiceResponseAsync(managementGroupName, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the management group. + * + * @param managementGroupName Management group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForManagementGroupWithServiceResponseAsync(final String managementGroupName, final QueryOptions queryOptions) { + return listQueryResultsForManagementGroupSinglePageAsync(managementGroupName, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForManagementGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the management group. + * + ServiceResponse> * @param managementGroupName Management group name. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForManagementGroupSinglePageAsync(final String managementGroupName, final QueryOptions queryOptions) { + if (managementGroupName == null) { + throw new IllegalArgumentException("Parameter managementGroupName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String managementGroupsNamespace = "Microsoft.Management"; + final String policyTrackedResourcesResource = "default"; + final String apiVersion = "2018-07-01-preview"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.listQueryResultsForManagementGroup(managementGroupsNamespace, managementGroupName, policyTrackedResourcesResource, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForManagementGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listQueryResultsForManagementGroupDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., QueryFailureException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForSubscription(final String subscriptionId) { + ServiceResponse> response = listQueryResultsForSubscriptionSinglePageAsync(subscriptionId).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForSubscriptionNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForSubscriptionAsync(final String subscriptionId, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForSubscriptionSinglePageAsync(subscriptionId), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForSubscriptionNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForSubscriptionAsync(final String subscriptionId) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(subscriptionId) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForSubscriptionWithServiceResponseAsync(final String subscriptionId) { + return listQueryResultsForSubscriptionSinglePageAsync(subscriptionId) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForSubscriptionNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForSubscriptionSinglePageAsync(final String subscriptionId) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + final String policyTrackedResourcesResource = "default"; + final String apiVersion = "2018-07-01-preview"; + final QueryOptions queryOptions = null; + Integer top = null; + String filter = null; + return service.listQueryResultsForSubscription(policyTrackedResourcesResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForSubscriptionDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForSubscription(final String subscriptionId, final QueryOptions queryOptions) { + ServiceResponse> response = listQueryResultsForSubscriptionSinglePageAsync(subscriptionId, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForSubscriptionNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForSubscriptionAsync(final String subscriptionId, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForSubscriptionSinglePageAsync(subscriptionId, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForSubscriptionNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForSubscriptionAsync(final String subscriptionId, final QueryOptions queryOptions) { + return listQueryResultsForSubscriptionWithServiceResponseAsync(subscriptionId, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForSubscriptionWithServiceResponseAsync(final String subscriptionId, final QueryOptions queryOptions) { + return listQueryResultsForSubscriptionSinglePageAsync(subscriptionId, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForSubscriptionNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the subscription. + * + ServiceResponse> * @param subscriptionId Microsoft Azure subscription ID. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForSubscriptionSinglePageAsync(final String subscriptionId, final QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyTrackedResourcesResource = "default"; + final String apiVersion = "2018-07-01-preview"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.listQueryResultsForSubscription(policyTrackedResourcesResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForSubscriptionDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listQueryResultsForSubscriptionDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., QueryFailureException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForResourceGroup(final String resourceGroupName, final String subscriptionId) { + ServiceResponse> response = listQueryResultsForResourceGroupSinglePageAsync(resourceGroupName, subscriptionId).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForResourceGroupAsync(final String resourceGroupName, final String subscriptionId, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForResourceGroupSinglePageAsync(resourceGroupName, subscriptionId), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForResourceGroupAsync(final String resourceGroupName, final String subscriptionId) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(resourceGroupName, subscriptionId) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForResourceGroupWithServiceResponseAsync(final String resourceGroupName, final String subscriptionId) { + return listQueryResultsForResourceGroupSinglePageAsync(resourceGroupName, subscriptionId) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForResourceGroupSinglePageAsync(final String resourceGroupName, final String subscriptionId) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + final String policyTrackedResourcesResource = "default"; + final String apiVersion = "2018-07-01-preview"; + final QueryOptions queryOptions = null; + Integer top = null; + String filter = null; + return service.listQueryResultsForResourceGroup(resourceGroupName, policyTrackedResourcesResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForResourceGroup(final String resourceGroupName, final String subscriptionId, final QueryOptions queryOptions) { + ServiceResponse> response = listQueryResultsForResourceGroupSinglePageAsync(resourceGroupName, subscriptionId, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForResourceGroupAsync(final String resourceGroupName, final String subscriptionId, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForResourceGroupSinglePageAsync(resourceGroupName, subscriptionId, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForResourceGroupAsync(final String resourceGroupName, final String subscriptionId, final QueryOptions queryOptions) { + return listQueryResultsForResourceGroupWithServiceResponseAsync(resourceGroupName, subscriptionId, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param resourceGroupName Resource group name. + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForResourceGroupWithServiceResponseAsync(final String resourceGroupName, final String subscriptionId, final QueryOptions queryOptions) { + return listQueryResultsForResourceGroupSinglePageAsync(resourceGroupName, subscriptionId, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the resource group. + * + ServiceResponse> * @param resourceGroupName Resource group name. + ServiceResponse> * @param subscriptionId Microsoft Azure subscription ID. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForResourceGroupSinglePageAsync(final String resourceGroupName, final String subscriptionId, final QueryOptions queryOptions) { + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyTrackedResourcesResource = "default"; + final String apiVersion = "2018-07-01-preview"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.listQueryResultsForResourceGroup(resourceGroupName, policyTrackedResourcesResource, subscriptionId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listQueryResultsForResourceGroupDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., QueryFailureException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForResource(final String resourceId) { + ServiceResponse> response = listQueryResultsForResourceSinglePageAsync(resourceId).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForResourceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForResourceAsync(final String resourceId, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForResourceSinglePageAsync(resourceId), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForResourceNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForResourceAsync(final String resourceId) { + return listQueryResultsForResourceWithServiceResponseAsync(resourceId) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForResourceWithServiceResponseAsync(final String resourceId) { + return listQueryResultsForResourceSinglePageAsync(resourceId) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForResourceNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForResourceSinglePageAsync(final String resourceId) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + final String policyTrackedResourcesResource = "default"; + final String apiVersion = "2018-07-01-preview"; + final QueryOptions queryOptions = null; + Integer top = null; + String filter = null; + return service.listQueryResultsForResource(resourceId, policyTrackedResourcesResource, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForResourceDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForResource(final String resourceId, final QueryOptions queryOptions) { + ServiceResponse> response = listQueryResultsForResourceSinglePageAsync(resourceId, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForResourceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForResourceAsync(final String resourceId, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForResourceSinglePageAsync(resourceId, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForResourceNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForResourceAsync(final String resourceId, final QueryOptions queryOptions) { + return listQueryResultsForResourceWithServiceResponseAsync(resourceId, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForResourceWithServiceResponseAsync(final String resourceId, final QueryOptions queryOptions) { + return listQueryResultsForResourceSinglePageAsync(resourceId, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForResourceNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the resource. + * + ServiceResponse> * @param resourceId Resource ID. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForResourceSinglePageAsync(final String resourceId, final QueryOptions queryOptions) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String policyTrackedResourcesResource = "default"; + final String apiVersion = "2018-07-01-preview"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.listQueryResultsForResource(resourceId, policyTrackedResourcesResource, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForResourceDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listQueryResultsForResourceDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., QueryFailureException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy tracked resources under the management group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForManagementGroupNext(final String nextPageLink) { + ServiceResponse> response = listQueryResultsForManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the management group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForManagementGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForManagementGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForManagementGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the management group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForManagementGroupNextAsync(final String nextPageLink) { + return listQueryResultsForManagementGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the management group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForManagementGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listQueryResultsForManagementGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForManagementGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the management group. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForManagementGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listQueryResultsForManagementGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForManagementGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listQueryResultsForManagementGroupNextDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., QueryFailureException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForSubscriptionNext(final String nextPageLink) { + ServiceResponse> response = listQueryResultsForSubscriptionNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForSubscriptionNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForSubscriptionNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForSubscriptionNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForSubscriptionNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForSubscriptionNextAsync(final String nextPageLink) { + return listQueryResultsForSubscriptionNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForSubscriptionNextWithServiceResponseAsync(final String nextPageLink) { + return listQueryResultsForSubscriptionNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForSubscriptionNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the subscription. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForSubscriptionNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listQueryResultsForSubscriptionNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForSubscriptionNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listQueryResultsForSubscriptionNextDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., QueryFailureException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForResourceGroupNext(final String nextPageLink) { + ServiceResponse> response = listQueryResultsForResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForResourceGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForResourceGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForResourceGroupNextAsync(final String nextPageLink) { + return listQueryResultsForResourceGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the resource group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForResourceGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listQueryResultsForResourceGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the resource group. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForResourceGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listQueryResultsForResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForResourceGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listQueryResultsForResourceGroupNextDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., QueryFailureException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @throws QueryFailureException thrown if the request is rejected by server + * @throws RuntimeException all other wrapped checked exceptions if the request fails to be sent + * @return the PagedList<PolicyTrackedResourceInner> object if successful. + */ + public PagedList listQueryResultsForResourceNext(final String nextPageLink) { + ServiceResponse> response = listQueryResultsForResourceNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listQueryResultsForResourceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Queries policy tracked resources under the resource. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listQueryResultsForResourceNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listQueryResultsForResourceNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listQueryResultsForResourceNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable> listQueryResultsForResourceNextAsync(final String nextPageLink) { + return listQueryResultsForResourceNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Queries policy tracked resources under the resource. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<PolicyTrackedResourceInner> object + */ + public Observable>> listQueryResultsForResourceNextWithServiceResponseAsync(final String nextPageLink) { + return listQueryResultsForResourceNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listQueryResultsForResourceNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Queries policy tracked resources under the resource. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<PolicyTrackedResourceInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listQueryResultsForResourceNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listQueryResultsForResourceNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listQueryResultsForResourceNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listQueryResultsForResourceNextDelegate(Response response) throws QueryFailureException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., QueryFailureException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(QueryFailureException.class) + .build(response); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationDeploymentImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationDeploymentImpl.java new file mode 100644 index 0000000000000..1061c5ff4f162 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationDeploymentImpl.java @@ -0,0 +1,63 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.RemediationDeployment; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import org.joda.time.DateTime; +import com.microsoft.azure.management.policyinsights.v2019_10_01.ErrorDefinition; + +class RemediationDeploymentImpl extends WrapperImpl implements RemediationDeployment { + private final PolicyInsightsManager manager; + RemediationDeploymentImpl(RemediationDeploymentInner inner, PolicyInsightsManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public DateTime createdOn() { + return this.inner().createdOn(); + } + + @Override + public String deploymentId() { + return this.inner().deploymentId(); + } + + @Override + public ErrorDefinition error() { + return this.inner().error(); + } + + @Override + public DateTime lastUpdatedOn() { + return this.inner().lastUpdatedOn(); + } + + @Override + public String remediatedResourceId() { + return this.inner().remediatedResourceId(); + } + + @Override + public String resourceLocation() { + return this.inner().resourceLocation(); + } + + @Override + public String status() { + return this.inner().status(); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationDeploymentInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationDeploymentInner.java new file mode 100644 index 0000000000000..58496d5084040 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationDeploymentInner.java @@ -0,0 +1,124 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.ErrorDefinition; +import org.joda.time.DateTime; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Details of a single deployment created by the remediation. + */ +public class RemediationDeploymentInner { + /** + * Resource ID of the resource that is being remediated by the deployment. + */ + @JsonProperty(value = "remediatedResourceId", access = JsonProperty.Access.WRITE_ONLY) + private String remediatedResourceId; + + /** + * Resource ID of the template deployment that will remediate the resource. + */ + @JsonProperty(value = "deploymentId", access = JsonProperty.Access.WRITE_ONLY) + private String deploymentId; + + /** + * Status of the remediation deployment. + */ + @JsonProperty(value = "status", access = JsonProperty.Access.WRITE_ONLY) + private String status; + + /** + * Location of the resource that is being remediated. + */ + @JsonProperty(value = "resourceLocation", access = JsonProperty.Access.WRITE_ONLY) + private String resourceLocation; + + /** + * Error encountered while remediated the resource. + */ + @JsonProperty(value = "error", access = JsonProperty.Access.WRITE_ONLY) + private ErrorDefinition error; + + /** + * The time at which the remediation was created. + */ + @JsonProperty(value = "createdOn", access = JsonProperty.Access.WRITE_ONLY) + private DateTime createdOn; + + /** + * The time at which the remediation deployment was last updated. + */ + @JsonProperty(value = "lastUpdatedOn", access = JsonProperty.Access.WRITE_ONLY) + private DateTime lastUpdatedOn; + + /** + * Get resource ID of the resource that is being remediated by the deployment. + * + * @return the remediatedResourceId value + */ + public String remediatedResourceId() { + return this.remediatedResourceId; + } + + /** + * Get resource ID of the template deployment that will remediate the resource. + * + * @return the deploymentId value + */ + public String deploymentId() { + return this.deploymentId; + } + + /** + * Get status of the remediation deployment. + * + * @return the status value + */ + public String status() { + return this.status; + } + + /** + * Get location of the resource that is being remediated. + * + * @return the resourceLocation value + */ + public String resourceLocation() { + return this.resourceLocation; + } + + /** + * Get error encountered while remediated the resource. + * + * @return the error value + */ + public ErrorDefinition error() { + return this.error; + } + + /** + * Get the time at which the remediation was created. + * + * @return the createdOn value + */ + public DateTime createdOn() { + return this.createdOn; + } + + /** + * Get the time at which the remediation deployment was last updated. + * + * @return the lastUpdatedOn value + */ + public DateTime lastUpdatedOn() { + return this.lastUpdatedOn; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationImpl.java new file mode 100644 index 0000000000000..396ef9972bc69 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationImpl.java @@ -0,0 +1,159 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.Remediation; +import com.microsoft.azure.arm.model.implementation.CreatableUpdatableImpl; +import rx.Observable; +import com.microsoft.azure.management.policyinsights.v2019_10_01.ResourceDiscoveryMode; +import org.joda.time.DateTime; +import com.microsoft.azure.management.policyinsights.v2019_10_01.RemediationFilters; +import com.microsoft.azure.management.policyinsights.v2019_10_01.RemediationDeploymentSummary; + +class RemediationImpl extends CreatableUpdatableImpl implements Remediation, Remediation.Definition, Remediation.Update { + private final PolicyInsightsManager manager; + private String managementGroupId; + private String remediationName; + + RemediationImpl(String name, PolicyInsightsManager manager) { + super(name, new RemediationInner()); + this.manager = manager; + // Set resource name + this.remediationName = name; + // + } + + RemediationImpl(RemediationInner inner, PolicyInsightsManager manager) { + super(inner.name(), inner); + this.manager = manager; + // Set resource name + this.remediationName = inner.name(); + // set resource ancestor and positional variables + this.managementGroupId = IdParsingUtils.getValueFromIdByName(inner.id(), "managementGroups"); + this.remediationName = IdParsingUtils.getValueFromIdByName(inner.id(), "remediations"); + // + } + + @Override + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public Observable createResourceAsync() { + RemediationsInner client = this.manager().inner().remediations(); + return client.createOrUpdateAtManagementGroupAsync(this.managementGroupId, this.remediationName, this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + public Observable updateResourceAsync() { + RemediationsInner client = this.manager().inner().remediations(); + return client.createOrUpdateAtManagementGroupAsync(this.managementGroupId, this.remediationName, this.inner()) + .map(innerToFluentMap(this)); + } + + @Override + protected Observable getInnerAsync() { + RemediationsInner client = this.manager().inner().remediations(); + return null; // NOP getInnerAsync implementation as get is not supported + } + + @Override + public boolean isInCreateMode() { + return this.inner().id() == null; + } + + + @Override + public DateTime createdOn() { + return this.inner().createdOn(); + } + + @Override + public RemediationDeploymentSummary deploymentStatus() { + return this.inner().deploymentStatus(); + } + + @Override + public RemediationFilters filters() { + return this.inner().filters(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public DateTime lastUpdatedOn() { + return this.inner().lastUpdatedOn(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public String policyAssignmentId() { + return this.inner().policyAssignmentId(); + } + + @Override + public String policyDefinitionReferenceId() { + return this.inner().policyDefinitionReferenceId(); + } + + @Override + public String provisioningState() { + return this.inner().provisioningState(); + } + + @Override + public ResourceDiscoveryMode resourceDiscoveryMode() { + return this.inner().resourceDiscoveryMode(); + } + + @Override + public String type() { + return this.inner().type(); + } + + @Override + public RemediationImpl withExistingManagementGroupId(String managementGroupId) { + this.managementGroupId = managementGroupId; + return this; + } + + @Override + public RemediationImpl withFilters(RemediationFilters filters) { + this.inner().withFilters(filters); + return this; + } + + @Override + public RemediationImpl withPolicyAssignmentId(String policyAssignmentId) { + this.inner().withPolicyAssignmentId(policyAssignmentId); + return this; + } + + @Override + public RemediationImpl withPolicyDefinitionReferenceId(String policyDefinitionReferenceId) { + this.inner().withPolicyDefinitionReferenceId(policyDefinitionReferenceId); + return this; + } + + @Override + public RemediationImpl withResourceDiscoveryMode(ResourceDiscoveryMode resourceDiscoveryMode) { + this.inner().withResourceDiscoveryMode(resourceDiscoveryMode); + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationInner.java new file mode 100644 index 0000000000000..8a035e0864efc --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationInner.java @@ -0,0 +1,194 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.ResourceDiscoveryMode; +import org.joda.time.DateTime; +import com.microsoft.azure.management.policyinsights.v2019_10_01.RemediationFilters; +import com.microsoft.azure.management.policyinsights.v2019_10_01.RemediationDeploymentSummary; +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; +import com.microsoft.azure.ProxyResource; + +/** + * The remediation definition. + */ +@JsonFlatten +public class RemediationInner extends ProxyResource { + /** + * The resource ID of the policy assignment that should be remediated. + */ + @JsonProperty(value = "properties.policyAssignmentId") + private String policyAssignmentId; + + /** + * The policy definition reference ID of the individual definition that + * should be remediated. Required when the policy assignment being + * remediated assigns a policy set definition. + */ + @JsonProperty(value = "properties.policyDefinitionReferenceId") + private String policyDefinitionReferenceId; + + /** + * The way resources to remediate are discovered. Defaults to + * ExistingNonCompliant if not specified. Possible values include: + * 'ExistingNonCompliant', 'ReEvaluateCompliance'. + */ + @JsonProperty(value = "properties.resourceDiscoveryMode") + private ResourceDiscoveryMode resourceDiscoveryMode; + + /** + * The status of the remediation. + */ + @JsonProperty(value = "properties.provisioningState", access = JsonProperty.Access.WRITE_ONLY) + private String provisioningState; + + /** + * The time at which the remediation was created. + */ + @JsonProperty(value = "properties.createdOn", access = JsonProperty.Access.WRITE_ONLY) + private DateTime createdOn; + + /** + * The time at which the remediation was last updated. + */ + @JsonProperty(value = "properties.lastUpdatedOn", access = JsonProperty.Access.WRITE_ONLY) + private DateTime lastUpdatedOn; + + /** + * The filters that will be applied to determine which resources to + * remediate. + */ + @JsonProperty(value = "properties.filters") + private RemediationFilters filters; + + /** + * The deployment status summary for all deployments created by the + * remediation. + */ + @JsonProperty(value = "properties.deploymentStatus", access = JsonProperty.Access.WRITE_ONLY) + private RemediationDeploymentSummary deploymentStatus; + + /** + * Get the resource ID of the policy assignment that should be remediated. + * + * @return the policyAssignmentId value + */ + public String policyAssignmentId() { + return this.policyAssignmentId; + } + + /** + * Set the resource ID of the policy assignment that should be remediated. + * + * @param policyAssignmentId the policyAssignmentId value to set + * @return the RemediationInner object itself. + */ + public RemediationInner withPolicyAssignmentId(String policyAssignmentId) { + this.policyAssignmentId = policyAssignmentId; + return this; + } + + /** + * Get the policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. + * + * @return the policyDefinitionReferenceId value + */ + public String policyDefinitionReferenceId() { + return this.policyDefinitionReferenceId; + } + + /** + * Set the policy definition reference ID of the individual definition that should be remediated. Required when the policy assignment being remediated assigns a policy set definition. + * + * @param policyDefinitionReferenceId the policyDefinitionReferenceId value to set + * @return the RemediationInner object itself. + */ + public RemediationInner withPolicyDefinitionReferenceId(String policyDefinitionReferenceId) { + this.policyDefinitionReferenceId = policyDefinitionReferenceId; + return this; + } + + /** + * Get the way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. Possible values include: 'ExistingNonCompliant', 'ReEvaluateCompliance'. + * + * @return the resourceDiscoveryMode value + */ + public ResourceDiscoveryMode resourceDiscoveryMode() { + return this.resourceDiscoveryMode; + } + + /** + * Set the way resources to remediate are discovered. Defaults to ExistingNonCompliant if not specified. Possible values include: 'ExistingNonCompliant', 'ReEvaluateCompliance'. + * + * @param resourceDiscoveryMode the resourceDiscoveryMode value to set + * @return the RemediationInner object itself. + */ + public RemediationInner withResourceDiscoveryMode(ResourceDiscoveryMode resourceDiscoveryMode) { + this.resourceDiscoveryMode = resourceDiscoveryMode; + return this; + } + + /** + * Get the status of the remediation. + * + * @return the provisioningState value + */ + public String provisioningState() { + return this.provisioningState; + } + + /** + * Get the time at which the remediation was created. + * + * @return the createdOn value + */ + public DateTime createdOn() { + return this.createdOn; + } + + /** + * Get the time at which the remediation was last updated. + * + * @return the lastUpdatedOn value + */ + public DateTime lastUpdatedOn() { + return this.lastUpdatedOn; + } + + /** + * Get the filters that will be applied to determine which resources to remediate. + * + * @return the filters value + */ + public RemediationFilters filters() { + return this.filters; + } + + /** + * Set the filters that will be applied to determine which resources to remediate. + * + * @param filters the filters value to set + * @return the RemediationInner object itself. + */ + public RemediationInner withFilters(RemediationFilters filters) { + this.filters = filters; + return this; + } + + /** + * Get the deployment status summary for all deployments created by the remediation. + * + * @return the deploymentStatus value + */ + public RemediationDeploymentSummary deploymentStatus() { + return this.deploymentStatus; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationsImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationsImpl.java new file mode 100644 index 0000000000000..ade9a3040cfaf --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationsImpl.java @@ -0,0 +1,369 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + * + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations; +import rx.functions.Func1; +import rx.Observable; +import com.microsoft.azure.Page; +import com.microsoft.azure.management.policyinsights.v2019_10_01.RemediationDeployment; +import com.microsoft.azure.management.policyinsights.v2019_10_01.Remediation; + +class RemediationsImpl extends WrapperImpl implements Remediations { + private final PolicyInsightsManager manager; + + RemediationsImpl(PolicyInsightsManager manager) { + super(manager.inner().remediations()); + this.manager = manager; + } + + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public RemediationImpl define(String name) { + return wrapModel(name); + } + + private RemediationImpl wrapModel(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + + private RemediationImpl wrapModel(String name) { + return new RemediationImpl(name, this.manager()); + } + + @Override + public Observable listDeploymentsAtManagementGroupAsync(final String managementGroupId, final String remediationName) { + RemediationsInner client = this.inner(); + return client.listDeploymentsAtManagementGroupAsync(managementGroupId, remediationName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public RemediationDeployment call(RemediationDeploymentInner inner) { + return new RemediationDeploymentImpl(inner, manager()); + } + }); + } + + @Override + public Observable cancelAtManagementGroupAsync(String managementGroupId, String remediationName) { + RemediationsInner client = this.inner(); + return client.cancelAtManagementGroupAsync(managementGroupId, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable listForManagementGroupAsync(final String managementGroupId) { + RemediationsInner client = this.inner(); + return client.listForManagementGroupAsync(managementGroupId) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable getAtManagementGroupAsync(String managementGroupId, String remediationName) { + RemediationsInner client = this.inner(); + return client.getAtManagementGroupAsync(managementGroupId, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable deleteAtManagementGroupAsync(String managementGroupId, String remediationName) { + RemediationsInner client = this.inner(); + return client.deleteAtManagementGroupAsync(managementGroupId, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable listDeploymentsAtSubscriptionAsync(final String subscriptionId, final String remediationName) { + RemediationsInner client = this.inner(); + return client.listDeploymentsAtSubscriptionAsync(subscriptionId, remediationName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public RemediationDeployment call(RemediationDeploymentInner inner) { + return new RemediationDeploymentImpl(inner, manager()); + } + }); + } + + @Override + public Observable cancelAtSubscriptionAsync(String subscriptionId, String remediationName) { + RemediationsInner client = this.inner(); + return client.cancelAtSubscriptionAsync(subscriptionId, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable createOrUpdateAtSubscriptionAsync(String subscriptionId, String remediationName, RemediationInner parameters) { + RemediationsInner client = this.inner(); + return client.createOrUpdateAtSubscriptionAsync(subscriptionId, remediationName, parameters) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable getAtSubscriptionAsync(String subscriptionId, String remediationName) { + RemediationsInner client = this.inner(); + return client.getAtSubscriptionAsync(subscriptionId, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable deleteAtSubscriptionAsync(String subscriptionId, String remediationName) { + RemediationsInner client = this.inner(); + return client.deleteAtSubscriptionAsync(subscriptionId, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable listDeploymentsAtResourceGroupAsync(final String subscriptionId, final String resourceGroupName, final String remediationName) { + RemediationsInner client = this.inner(); + return client.listDeploymentsAtResourceGroupAsync(subscriptionId, resourceGroupName, remediationName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public RemediationDeployment call(RemediationDeploymentInner inner) { + return new RemediationDeploymentImpl(inner, manager()); + } + }); + } + + @Override + public Observable cancelAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName) { + RemediationsInner client = this.inner(); + return client.cancelAtResourceGroupAsync(subscriptionId, resourceGroupName, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable createOrUpdateAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName, RemediationInner parameters) { + RemediationsInner client = this.inner(); + return client.createOrUpdateAtResourceGroupAsync(subscriptionId, resourceGroupName, remediationName, parameters) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable getByResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName) { + RemediationsInner client = this.inner(); + return client.getByResourceGroupAsync(subscriptionId, resourceGroupName, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable deleteAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName) { + RemediationsInner client = this.inner(); + return client.deleteAtResourceGroupAsync(subscriptionId, resourceGroupName, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable listDeploymentsAtResourceAsync(final String resourceId, final String remediationName) { + RemediationsInner client = this.inner(); + return client.listDeploymentsAtResourceAsync(resourceId, remediationName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public RemediationDeployment call(RemediationDeploymentInner inner) { + return new RemediationDeploymentImpl(inner, manager()); + } + }); + } + + @Override + public Observable cancelAtResourceAsync(String resourceId, String remediationName) { + RemediationsInner client = this.inner(); + return client.cancelAtResourceAsync(resourceId, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable createOrUpdateAtResourceAsync(String resourceId, String remediationName, RemediationInner parameters) { + RemediationsInner client = this.inner(); + return client.createOrUpdateAtResourceAsync(resourceId, remediationName, parameters) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable getAtResourceAsync(String resourceId, String remediationName) { + RemediationsInner client = this.inner(); + return client.getAtResourceAsync(resourceId, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable deleteAtResourceAsync(String resourceId, String remediationName) { + RemediationsInner client = this.inner(); + return client.deleteAtResourceAsync(resourceId, remediationName) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable listAsync(final String subscriptionId) { + RemediationsInner client = this.inner(); + return client.listAsync(subscriptionId) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable listByResourceGroupAsync(final String subscriptionId, final String resourceGroupName) { + RemediationsInner client = this.inner(); + return client.listByResourceGroupAsync(subscriptionId, resourceGroupName) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + + @Override + public Observable listForResourceAsync(final String resourceId) { + RemediationsInner client = this.inner(); + return client.listForResourceAsync(resourceId) + .flatMapIterable(new Func1, Iterable>() { + @Override + public Iterable call(Page page) { + return page.items(); + } + }) + .map(new Func1() { + @Override + public Remediation call(RemediationInner inner) { + return new RemediationImpl(inner, manager()); + } + }); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationsInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationsInner.java new file mode 100644 index 0000000000000..517af2c2ac5f0 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/RemediationsInner.java @@ -0,0 +1,4372 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import retrofit2.Retrofit; +import com.google.common.reflect.TypeToken; +import com.microsoft.azure.AzureServiceFuture; +import com.microsoft.azure.ListOperationCallback; +import com.microsoft.azure.management.policyinsights.v2019_10_01.ErrorResponseException; +import com.microsoft.azure.management.policyinsights.v2019_10_01.QueryOptions; +import com.microsoft.azure.Page; +import com.microsoft.azure.PagedList; +import com.microsoft.rest.ServiceCallback; +import com.microsoft.rest.ServiceFuture; +import com.microsoft.rest.ServiceResponse; +import com.microsoft.rest.Validator; +import java.io.IOException; +import java.util.List; +import okhttp3.ResponseBody; +import retrofit2.http.Body; +import retrofit2.http.GET; +import retrofit2.http.Header; +import retrofit2.http.Headers; +import retrofit2.http.HTTP; +import retrofit2.http.Path; +import retrofit2.http.POST; +import retrofit2.http.PUT; +import retrofit2.http.Query; +import retrofit2.http.Url; +import retrofit2.Response; +import rx.functions.Func1; +import rx.Observable; + +/** + * An instance of this class provides access to all the operations defined + * in Remediations. + */ +public class RemediationsInner { + /** The Retrofit service to perform REST calls. */ + private RemediationsService service; + /** The service client containing this operation class. */ + private PolicyInsightsClientImpl client; + + /** + * Initializes an instance of RemediationsInner. + * + * @param retrofit the Retrofit instance built from a Retrofit Builder. + * @param client the instance of the service client containing this operation class. + */ + public RemediationsInner(Retrofit retrofit, PolicyInsightsClientImpl client) { + this.service = retrofit.create(RemediationsService.class); + this.client = client; + } + + /** + * The interface defining all the services for Remediations to be + * used by Retrofit to perform actually REST calls. + */ + interface RemediationsService { + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listDeploymentsAtManagementGroup" }) + @POST("providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments") + Observable> listDeploymentsAtManagementGroup(@Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupId") String managementGroupId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations cancelAtManagementGroup" }) + @POST("providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel") + Observable> cancelAtManagementGroup(@Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupId") String managementGroupId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listForManagementGroup" }) + @GET("providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations") + Observable> listForManagementGroup(@Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupId") String managementGroupId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations createOrUpdateAtManagementGroup" }) + @PUT("providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + Observable> createOrUpdateAtManagementGroup(@Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupId") String managementGroupId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Body RemediationInner parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations getAtManagementGroup" }) + @GET("providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + Observable> getAtManagementGroup(@Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupId") String managementGroupId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations deleteAtManagementGroup" }) + @HTTP(path = "providers/{managementGroupsNamespace}/managementGroups/{managementGroupId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", method = "DELETE", hasBody = true) + Observable> deleteAtManagementGroup(@Path("managementGroupsNamespace") String managementGroupsNamespace, @Path("managementGroupId") String managementGroupId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listDeploymentsAtSubscription" }) + @POST("subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments") + Observable> listDeploymentsAtSubscription(@Path("subscriptionId") String subscriptionId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations cancelAtSubscription" }) + @POST("subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel") + Observable> cancelAtSubscription(@Path("subscriptionId") String subscriptionId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations list" }) + @GET("subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations") + Observable> list(@Path("subscriptionId") String subscriptionId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations createOrUpdateAtSubscription" }) + @PUT("subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + Observable> createOrUpdateAtSubscription(@Path("subscriptionId") String subscriptionId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Body RemediationInner parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations getAtSubscription" }) + @GET("subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + Observable> getAtSubscription(@Path("subscriptionId") String subscriptionId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations deleteAtSubscription" }) + @HTTP(path = "subscriptions/{subscriptionId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", method = "DELETE", hasBody = true) + Observable> deleteAtSubscription(@Path("subscriptionId") String subscriptionId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listDeploymentsAtResourceGroup" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments") + Observable> listDeploymentsAtResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations cancelAtResourceGroup" }) + @POST("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel") + Observable> cancelAtResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listByResourceGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations") + Observable> listByResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations createOrUpdateAtResourceGroup" }) + @PUT("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + Observable> createOrUpdateAtResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Body RemediationInner parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations getByResourceGroup" }) + @GET("subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + Observable> getByResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations deleteAtResourceGroup" }) + @HTTP(path = "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", method = "DELETE", hasBody = true) + Observable> deleteAtResourceGroup(@Path("subscriptionId") String subscriptionId, @Path("resourceGroupName") String resourceGroupName, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listDeploymentsAtResource" }) + @POST("{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/listDeployments") + Observable> listDeploymentsAtResource(@Path(value = "resourceId", encoded = true) String resourceId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations cancelAtResource" }) + @POST("{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}/cancel") + Observable> cancelAtResource(@Path(value = "resourceId", encoded = true) String resourceId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listForResource" }) + @GET("{resourceId}/providers/Microsoft.PolicyInsights/remediations") + Observable> listForResource(@Path(value = "resourceId", encoded = true) String resourceId, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Query("$top") Integer top, @Query("$filter") String filter, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations createOrUpdateAtResource" }) + @PUT("{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + Observable> createOrUpdateAtResource(@Path(value = "resourceId", encoded = true) String resourceId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Body RemediationInner parameters, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations getAtResource" }) + @GET("{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}") + Observable> getAtResource(@Path(value = "resourceId", encoded = true) String resourceId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations deleteAtResource" }) + @HTTP(path = "{resourceId}/providers/Microsoft.PolicyInsights/remediations/{remediationName}", method = "DELETE", hasBody = true) + Observable> deleteAtResource(@Path(value = "resourceId", encoded = true) String resourceId, @Path("remediationName") String remediationName, @Query("api-version") String apiVersion, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listDeploymentsAtManagementGroupNext" }) + @GET + Observable> listDeploymentsAtManagementGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listForManagementGroupNext" }) + @GET + Observable> listForManagementGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listDeploymentsAtSubscriptionNext" }) + @GET + Observable> listDeploymentsAtSubscriptionNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listNext" }) + @GET + Observable> listNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listDeploymentsAtResourceGroupNext" }) + @GET + Observable> listDeploymentsAtResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listByResourceGroupNext" }) + @GET + Observable> listByResourceGroupNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listDeploymentsAtResourceNext" }) + @GET + Observable> listDeploymentsAtResourceNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + @Headers({ "Content-Type: application/json; charset=utf-8", "x-ms-logging-context: com.microsoft.azure.management.policyinsights.v2019_10_01.Remediations listForResourceNext" }) + @GET + Observable> listForResourceNext(@Url String nextUrl, @Header("accept-language") String acceptLanguage, @Header("User-Agent") String userAgent); + + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtManagementGroup(final String managementGroupId, final String remediationName) { + ServiceResponse> response = listDeploymentsAtManagementGroupSinglePageAsync(managementGroupId, remediationName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtManagementGroupAsync(final String managementGroupId, final String remediationName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtManagementGroupSinglePageAsync(managementGroupId, remediationName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtManagementGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtManagementGroupAsync(final String managementGroupId, final String remediationName) { + return listDeploymentsAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtManagementGroupWithServiceResponseAsync(final String managementGroupId, final String remediationName) { + return listDeploymentsAtManagementGroupSinglePageAsync(managementGroupId, remediationName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtManagementGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtManagementGroupSinglePageAsync(final String managementGroupId, final String remediationName) { + if (managementGroupId == null) { + throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-07-01"; + final QueryOptions queryOptions = null; + Integer top = null; + return service.listDeploymentsAtManagementGroup(managementGroupsNamespace, managementGroupId, remediationName, apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtManagementGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtManagementGroup(final String managementGroupId, final String remediationName, final QueryOptions queryOptions) { + ServiceResponse> response = listDeploymentsAtManagementGroupSinglePageAsync(managementGroupId, remediationName, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtManagementGroupAsync(final String managementGroupId, final String remediationName, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtManagementGroupSinglePageAsync(managementGroupId, remediationName, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtManagementGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtManagementGroupAsync(final String managementGroupId, final String remediationName, final QueryOptions queryOptions) { + return listDeploymentsAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtManagementGroupWithServiceResponseAsync(final String managementGroupId, final String remediationName, final QueryOptions queryOptions) { + return listDeploymentsAtManagementGroupSinglePageAsync(managementGroupId, remediationName, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtManagementGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + ServiceResponse> * @param managementGroupId Management group ID. + ServiceResponse> * @param remediationName The name of the remediation. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtManagementGroupSinglePageAsync(final String managementGroupId, final String remediationName, final QueryOptions queryOptions) { + if (managementGroupId == null) { + throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-07-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + return service.listDeploymentsAtManagementGroup(managementGroupsNamespace, managementGroupId, remediationName, apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtManagementGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDeploymentsAtManagementGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Cancels a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner cancelAtManagementGroup(String managementGroupId, String remediationName) { + return cancelAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName).toBlocking().single().body(); + } + + /** + * Cancels a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture cancelAtManagementGroupAsync(String managementGroupId, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(cancelAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName), serviceCallback); + } + + /** + * Cancels a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable cancelAtManagementGroupAsync(String managementGroupId, String remediationName) { + return cancelAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Cancels a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> cancelAtManagementGroupWithServiceResponseAsync(String managementGroupId, String remediationName) { + if (managementGroupId == null) { + throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-07-01"; + return service.cancelAtManagementGroup(managementGroupsNamespace, managementGroupId, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = cancelAtManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse cancelAtManagementGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listForManagementGroup(final String managementGroupId) { + ServiceResponse> response = listForManagementGroupSinglePageAsync(managementGroupId).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listForManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listForManagementGroupAsync(final String managementGroupId, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listForManagementGroupSinglePageAsync(managementGroupId), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listForManagementGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listForManagementGroupAsync(final String managementGroupId) { + return listForManagementGroupWithServiceResponseAsync(managementGroupId) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listForManagementGroupWithServiceResponseAsync(final String managementGroupId) { + return listForManagementGroupSinglePageAsync(managementGroupId) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listForManagementGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listForManagementGroupSinglePageAsync(final String managementGroupId) { + if (managementGroupId == null) { + throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null."); + } + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-07-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String filter = null; + return service.listForManagementGroup(managementGroupsNamespace, managementGroupId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listForManagementGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @param queryOptions Additional parameters for the operation + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listForManagementGroup(final String managementGroupId, final QueryOptions queryOptions) { + ServiceResponse> response = listForManagementGroupSinglePageAsync(managementGroupId, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listForManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listForManagementGroupAsync(final String managementGroupId, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listForManagementGroupSinglePageAsync(managementGroupId, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listForManagementGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listForManagementGroupAsync(final String managementGroupId, final QueryOptions queryOptions) { + return listForManagementGroupWithServiceResponseAsync(managementGroupId, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for the management group. + * + * @param managementGroupId Management group ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listForManagementGroupWithServiceResponseAsync(final String managementGroupId, final QueryOptions queryOptions) { + return listForManagementGroupSinglePageAsync(managementGroupId, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listForManagementGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for the management group. + * + ServiceResponse> * @param managementGroupId Management group ID. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listForManagementGroupSinglePageAsync(final String managementGroupId, final QueryOptions queryOptions) { + if (managementGroupId == null) { + throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-07-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.listForManagementGroup(managementGroupsNamespace, managementGroupId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listForManagementGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listForManagementGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Creates or updates a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner createOrUpdateAtManagementGroup(String managementGroupId, String remediationName, RemediationInner parameters) { + return createOrUpdateAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName, parameters).toBlocking().single().body(); + } + + /** + * Creates or updates a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAtManagementGroupAsync(String managementGroupId, String remediationName, RemediationInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName, parameters), serviceCallback); + } + + /** + * Creates or updates a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable createOrUpdateAtManagementGroupAsync(String managementGroupId, String remediationName, RemediationInner parameters) { + return createOrUpdateAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName, parameters).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates a remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> createOrUpdateAtManagementGroupWithServiceResponseAsync(String managementGroupId, String remediationName, RemediationInner parameters) { + if (managementGroupId == null) { + throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + Validator.validate(parameters); + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-07-01"; + return service.createOrUpdateAtManagementGroup(managementGroupsNamespace, managementGroupId, remediationName, apiVersion, parameters, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createOrUpdateAtManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse createOrUpdateAtManagementGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner getAtManagementGroup(String managementGroupId, String remediationName) { + return getAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName).toBlocking().single().body(); + } + + /** + * Gets an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAtManagementGroupAsync(String managementGroupId, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName), serviceCallback); + } + + /** + * Gets an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable getAtManagementGroupAsync(String managementGroupId, String remediationName) { + return getAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> getAtManagementGroupWithServiceResponseAsync(String managementGroupId, String remediationName) { + if (managementGroupId == null) { + throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-07-01"; + return service.getAtManagementGroup(managementGroupsNamespace, managementGroupId, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getAtManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getAtManagementGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Deletes an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner deleteAtManagementGroup(String managementGroupId, String remediationName) { + return deleteAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName).toBlocking().single().body(); + } + + /** + * Deletes an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAtManagementGroupAsync(String managementGroupId, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName), serviceCallback); + } + + /** + * Deletes an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable deleteAtManagementGroupAsync(String managementGroupId, String remediationName) { + return deleteAtManagementGroupWithServiceResponseAsync(managementGroupId, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes an existing remediation at management group scope. + * + * @param managementGroupId Management group ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> deleteAtManagementGroupWithServiceResponseAsync(String managementGroupId, String remediationName) { + if (managementGroupId == null) { + throw new IllegalArgumentException("Parameter managementGroupId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String managementGroupsNamespace = "Microsoft.Management"; + final String apiVersion = "2019-07-01"; + return service.deleteAtManagementGroup(managementGroupsNamespace, managementGroupId, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteAtManagementGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse deleteAtManagementGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtSubscription(final String subscriptionId, final String remediationName) { + ServiceResponse> response = listDeploymentsAtSubscriptionSinglePageAsync(subscriptionId, remediationName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtSubscriptionNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtSubscriptionAsync(final String subscriptionId, final String remediationName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtSubscriptionSinglePageAsync(subscriptionId, remediationName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtSubscriptionNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtSubscriptionAsync(final String subscriptionId, final String remediationName) { + return listDeploymentsAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtSubscriptionWithServiceResponseAsync(final String subscriptionId, final String remediationName) { + return listDeploymentsAtSubscriptionSinglePageAsync(subscriptionId, remediationName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtSubscriptionNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtSubscriptionSinglePageAsync(final String subscriptionId, final String remediationName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + final QueryOptions queryOptions = null; + Integer top = null; + return service.listDeploymentsAtSubscription(subscriptionId, remediationName, apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtSubscriptionDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtSubscription(final String subscriptionId, final String remediationName, final QueryOptions queryOptions) { + ServiceResponse> response = listDeploymentsAtSubscriptionSinglePageAsync(subscriptionId, remediationName, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtSubscriptionNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtSubscriptionAsync(final String subscriptionId, final String remediationName, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtSubscriptionSinglePageAsync(subscriptionId, remediationName, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtSubscriptionNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtSubscriptionAsync(final String subscriptionId, final String remediationName, final QueryOptions queryOptions) { + return listDeploymentsAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtSubscriptionWithServiceResponseAsync(final String subscriptionId, final String remediationName, final QueryOptions queryOptions) { + return listDeploymentsAtSubscriptionSinglePageAsync(subscriptionId, remediationName, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtSubscriptionNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + ServiceResponse> * @param subscriptionId Microsoft Azure subscription ID. + ServiceResponse> * @param remediationName The name of the remediation. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtSubscriptionSinglePageAsync(final String subscriptionId, final String remediationName, final QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String apiVersion = "2019-07-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + return service.listDeploymentsAtSubscription(subscriptionId, remediationName, apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtSubscriptionDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDeploymentsAtSubscriptionDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Cancels a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner cancelAtSubscription(String subscriptionId, String remediationName) { + return cancelAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName).toBlocking().single().body(); + } + + /** + * Cancels a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture cancelAtSubscriptionAsync(String subscriptionId, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(cancelAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName), serviceCallback); + } + + /** + * Cancels a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable cancelAtSubscriptionAsync(String subscriptionId, String remediationName) { + return cancelAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Cancels a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> cancelAtSubscriptionWithServiceResponseAsync(String subscriptionId, String remediationName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + return service.cancelAtSubscription(subscriptionId, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = cancelAtSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse cancelAtSubscriptionDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList list(final String subscriptionId) { + ServiceResponse> response = listSinglePageAsync(subscriptionId).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final String subscriptionId, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(subscriptionId), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listAsync(final String subscriptionId) { + return listWithServiceResponseAsync(subscriptionId) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listWithServiceResponseAsync(final String subscriptionId) { + return listSinglePageAsync(subscriptionId) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final String subscriptionId) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String filter = null; + return service.list(subscriptionId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList list(final String subscriptionId, final QueryOptions queryOptions) { + ServiceResponse> response = listSinglePageAsync(subscriptionId, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listAsync(final String subscriptionId, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listSinglePageAsync(subscriptionId, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listAsync(final String subscriptionId, final QueryOptions queryOptions) { + return listWithServiceResponseAsync(subscriptionId, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listWithServiceResponseAsync(final String subscriptionId, final QueryOptions queryOptions) { + return listSinglePageAsync(subscriptionId, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + ServiceResponse> * @param subscriptionId Microsoft Azure subscription ID. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listSinglePageAsync(final String subscriptionId, final QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String apiVersion = "2019-07-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.list(subscriptionId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Creates or updates a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner createOrUpdateAtSubscription(String subscriptionId, String remediationName, RemediationInner parameters) { + return createOrUpdateAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName, parameters).toBlocking().single().body(); + } + + /** + * Creates or updates a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAtSubscriptionAsync(String subscriptionId, String remediationName, RemediationInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName, parameters), serviceCallback); + } + + /** + * Creates or updates a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable createOrUpdateAtSubscriptionAsync(String subscriptionId, String remediationName, RemediationInner parameters) { + return createOrUpdateAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName, parameters).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates a remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> createOrUpdateAtSubscriptionWithServiceResponseAsync(String subscriptionId, String remediationName, RemediationInner parameters) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + Validator.validate(parameters); + final String apiVersion = "2019-07-01"; + return service.createOrUpdateAtSubscription(subscriptionId, remediationName, apiVersion, parameters, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createOrUpdateAtSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse createOrUpdateAtSubscriptionDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner getAtSubscription(String subscriptionId, String remediationName) { + return getAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName).toBlocking().single().body(); + } + + /** + * Gets an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAtSubscriptionAsync(String subscriptionId, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName), serviceCallback); + } + + /** + * Gets an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable getAtSubscriptionAsync(String subscriptionId, String remediationName) { + return getAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> getAtSubscriptionWithServiceResponseAsync(String subscriptionId, String remediationName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + return service.getAtSubscription(subscriptionId, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getAtSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getAtSubscriptionDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Deletes an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner deleteAtSubscription(String subscriptionId, String remediationName) { + return deleteAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName).toBlocking().single().body(); + } + + /** + * Deletes an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAtSubscriptionAsync(String subscriptionId, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName), serviceCallback); + } + + /** + * Deletes an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable deleteAtSubscriptionAsync(String subscriptionId, String remediationName) { + return deleteAtSubscriptionWithServiceResponseAsync(subscriptionId, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes an existing remediation at subscription scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> deleteAtSubscriptionWithServiceResponseAsync(String subscriptionId, String remediationName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + return service.deleteAtSubscription(subscriptionId, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteAtSubscriptionDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse deleteAtSubscriptionDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtResourceGroup(final String subscriptionId, final String resourceGroupName, final String remediationName) { + ServiceResponse> response = listDeploymentsAtResourceGroupSinglePageAsync(subscriptionId, resourceGroupName, remediationName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtResourceGroupAsync(final String subscriptionId, final String resourceGroupName, final String remediationName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtResourceGroupSinglePageAsync(subscriptionId, resourceGroupName, remediationName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtResourceGroupAsync(final String subscriptionId, final String resourceGroupName, final String remediationName) { + return listDeploymentsAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtResourceGroupWithServiceResponseAsync(final String subscriptionId, final String resourceGroupName, final String remediationName) { + return listDeploymentsAtResourceGroupSinglePageAsync(subscriptionId, resourceGroupName, remediationName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtResourceGroupSinglePageAsync(final String subscriptionId, final String resourceGroupName, final String remediationName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + final QueryOptions queryOptions = null; + Integer top = null; + return service.listDeploymentsAtResourceGroup(subscriptionId, resourceGroupName, remediationName, apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtResourceGroup(final String subscriptionId, final String resourceGroupName, final String remediationName, final QueryOptions queryOptions) { + ServiceResponse> response = listDeploymentsAtResourceGroupSinglePageAsync(subscriptionId, resourceGroupName, remediationName, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtResourceGroupAsync(final String subscriptionId, final String resourceGroupName, final String remediationName, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtResourceGroupSinglePageAsync(subscriptionId, resourceGroupName, remediationName, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtResourceGroupAsync(final String subscriptionId, final String resourceGroupName, final String remediationName, final QueryOptions queryOptions) { + return listDeploymentsAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtResourceGroupWithServiceResponseAsync(final String subscriptionId, final String resourceGroupName, final String remediationName, final QueryOptions queryOptions) { + return listDeploymentsAtResourceGroupSinglePageAsync(subscriptionId, resourceGroupName, remediationName, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + ServiceResponse> * @param subscriptionId Microsoft Azure subscription ID. + ServiceResponse> * @param resourceGroupName Resource group name. + ServiceResponse> * @param remediationName The name of the remediation. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtResourceGroupSinglePageAsync(final String subscriptionId, final String resourceGroupName, final String remediationName, final QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String apiVersion = "2019-07-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + return service.listDeploymentsAtResourceGroup(subscriptionId, resourceGroupName, remediationName, apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDeploymentsAtResourceGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Cancels a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner cancelAtResourceGroup(String subscriptionId, String resourceGroupName, String remediationName) { + return cancelAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName).toBlocking().single().body(); + } + + /** + * Cancels a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture cancelAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(cancelAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName), serviceCallback); + } + + /** + * Cancels a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable cancelAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName) { + return cancelAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Cancels a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> cancelAtResourceGroupWithServiceResponseAsync(String subscriptionId, String resourceGroupName, String remediationName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + return service.cancelAtResourceGroup(subscriptionId, resourceGroupName, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = cancelAtResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse cancelAtResourceGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listByResourceGroup(final String subscriptionId, final String resourceGroupName) { + ServiceResponse> response = listByResourceGroupSinglePageAsync(subscriptionId, resourceGroupName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupAsync(final String subscriptionId, final String resourceGroupName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByResourceGroupSinglePageAsync(subscriptionId, resourceGroupName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listByResourceGroupAsync(final String subscriptionId, final String resourceGroupName) { + return listByResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listByResourceGroupWithServiceResponseAsync(final String subscriptionId, final String resourceGroupName) { + return listByResourceGroupSinglePageAsync(subscriptionId, resourceGroupName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupSinglePageAsync(final String subscriptionId, final String resourceGroupName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String filter = null; + return service.listByResourceGroup(subscriptionId, resourceGroupName, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listByResourceGroup(final String subscriptionId, final String resourceGroupName, final QueryOptions queryOptions) { + ServiceResponse> response = listByResourceGroupSinglePageAsync(subscriptionId, resourceGroupName, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupAsync(final String subscriptionId, final String resourceGroupName, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByResourceGroupSinglePageAsync(subscriptionId, resourceGroupName, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listByResourceGroupAsync(final String subscriptionId, final String resourceGroupName, final QueryOptions queryOptions) { + return listByResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listByResourceGroupWithServiceResponseAsync(final String subscriptionId, final String resourceGroupName, final QueryOptions queryOptions) { + return listByResourceGroupSinglePageAsync(subscriptionId, resourceGroupName, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + ServiceResponse> * @param subscriptionId Microsoft Azure subscription ID. + ServiceResponse> * @param resourceGroupName Resource group name. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupSinglePageAsync(final String subscriptionId, final String resourceGroupName, final QueryOptions queryOptions) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String apiVersion = "2019-07-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.listByResourceGroup(subscriptionId, resourceGroupName, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByResourceGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Creates or updates a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner createOrUpdateAtResourceGroup(String subscriptionId, String resourceGroupName, String remediationName, RemediationInner parameters) { + return createOrUpdateAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName, parameters).toBlocking().single().body(); + } + + /** + * Creates or updates a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName, RemediationInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName, parameters), serviceCallback); + } + + /** + * Creates or updates a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable createOrUpdateAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName, RemediationInner parameters) { + return createOrUpdateAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName, parameters).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates a remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> createOrUpdateAtResourceGroupWithServiceResponseAsync(String subscriptionId, String resourceGroupName, String remediationName, RemediationInner parameters) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + Validator.validate(parameters); + final String apiVersion = "2019-07-01"; + return service.createOrUpdateAtResourceGroup(subscriptionId, resourceGroupName, remediationName, apiVersion, parameters, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createOrUpdateAtResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse createOrUpdateAtResourceGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner getByResourceGroup(String subscriptionId, String resourceGroupName, String remediationName) { + return getByResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName).toBlocking().single().body(); + } + + /** + * Gets an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getByResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getByResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName), serviceCallback); + } + + /** + * Gets an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable getByResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName) { + return getByResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> getByResourceGroupWithServiceResponseAsync(String subscriptionId, String resourceGroupName, String remediationName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + return service.getByResourceGroup(subscriptionId, resourceGroupName, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getByResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getByResourceGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Deletes an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner deleteAtResourceGroup(String subscriptionId, String resourceGroupName, String remediationName) { + return deleteAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName).toBlocking().single().body(); + } + + /** + * Deletes an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName), serviceCallback); + } + + /** + * Deletes an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable deleteAtResourceGroupAsync(String subscriptionId, String resourceGroupName, String remediationName) { + return deleteAtResourceGroupWithServiceResponseAsync(subscriptionId, resourceGroupName, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes an existing remediation at resource group scope. + * + * @param subscriptionId Microsoft Azure subscription ID. + * @param resourceGroupName Resource group name. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> deleteAtResourceGroupWithServiceResponseAsync(String subscriptionId, String resourceGroupName, String remediationName) { + if (subscriptionId == null) { + throw new IllegalArgumentException("Parameter subscriptionId is required and cannot be null."); + } + if (resourceGroupName == null) { + throw new IllegalArgumentException("Parameter resourceGroupName is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + return service.deleteAtResourceGroup(subscriptionId, resourceGroupName, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteAtResourceGroupDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse deleteAtResourceGroupDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtResource(final String resourceId, final String remediationName) { + ServiceResponse> response = listDeploymentsAtResourceSinglePageAsync(resourceId, remediationName).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtResourceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtResourceAsync(final String resourceId, final String remediationName, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtResourceSinglePageAsync(resourceId, remediationName), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtResourceNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtResourceAsync(final String resourceId, final String remediationName) { + return listDeploymentsAtResourceWithServiceResponseAsync(resourceId, remediationName) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtResourceWithServiceResponseAsync(final String resourceId, final String remediationName) { + return listDeploymentsAtResourceSinglePageAsync(resourceId, remediationName) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtResourceNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtResourceSinglePageAsync(final String resourceId, final String remediationName) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + final QueryOptions queryOptions = null; + Integer top = null; + return service.listDeploymentsAtResource(resourceId, remediationName, apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtResourceDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtResource(final String resourceId, final String remediationName, final QueryOptions queryOptions) { + ServiceResponse> response = listDeploymentsAtResourceSinglePageAsync(resourceId, remediationName, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtResourceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtResourceAsync(final String resourceId, final String remediationName, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtResourceSinglePageAsync(resourceId, remediationName, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtResourceNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtResourceAsync(final String resourceId, final String remediationName, final QueryOptions queryOptions) { + return listDeploymentsAtResourceWithServiceResponseAsync(resourceId, remediationName, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtResourceWithServiceResponseAsync(final String resourceId, final String remediationName, final QueryOptions queryOptions) { + return listDeploymentsAtResourceSinglePageAsync(resourceId, remediationName, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtResourceNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + ServiceResponse> * @param resourceId Resource ID. + ServiceResponse> * @param remediationName The name of the remediation. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtResourceSinglePageAsync(final String resourceId, final String remediationName, final QueryOptions queryOptions) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + Validator.validate(queryOptions); + final String apiVersion = "2019-07-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + return service.listDeploymentsAtResource(resourceId, remediationName, apiVersion, this.client.acceptLanguage(), top, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtResourceDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDeploymentsAtResourceDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Cancel a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner cancelAtResource(String resourceId, String remediationName) { + return cancelAtResourceWithServiceResponseAsync(resourceId, remediationName).toBlocking().single().body(); + } + + /** + * Cancel a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture cancelAtResourceAsync(String resourceId, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(cancelAtResourceWithServiceResponseAsync(resourceId, remediationName), serviceCallback); + } + + /** + * Cancel a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable cancelAtResourceAsync(String resourceId, String remediationName) { + return cancelAtResourceWithServiceResponseAsync(resourceId, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Cancel a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> cancelAtResourceWithServiceResponseAsync(String resourceId, String remediationName) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + return service.cancelAtResource(resourceId, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = cancelAtResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse cancelAtResourceDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listForResource(final String resourceId) { + ServiceResponse> response = listForResourceSinglePageAsync(resourceId).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listForResourceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listForResourceAsync(final String resourceId, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listForResourceSinglePageAsync(resourceId), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listForResourceNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listForResourceAsync(final String resourceId) { + return listForResourceWithServiceResponseAsync(resourceId) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listForResourceWithServiceResponseAsync(final String resourceId) { + return listForResourceSinglePageAsync(resourceId) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listForResourceNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listForResourceSinglePageAsync(final String resourceId) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + final QueryOptions queryOptions = null; + Integer top = null; + String filter = null; + return service.listForResource(resourceId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listForResourceDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listForResource(final String resourceId, final QueryOptions queryOptions) { + ServiceResponse> response = listForResourceSinglePageAsync(resourceId, queryOptions).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listForResourceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listForResourceAsync(final String resourceId, final QueryOptions queryOptions, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listForResourceSinglePageAsync(resourceId, queryOptions), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listForResourceNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listForResourceAsync(final String resourceId, final QueryOptions queryOptions) { + return listForResourceWithServiceResponseAsync(resourceId, queryOptions) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for a resource. + * + * @param resourceId Resource ID. + * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listForResourceWithServiceResponseAsync(final String resourceId, final QueryOptions queryOptions) { + return listForResourceSinglePageAsync(resourceId, queryOptions) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listForResourceNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for a resource. + * + ServiceResponse> * @param resourceId Resource ID. + ServiceResponse> * @param queryOptions Additional parameters for the operation + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listForResourceSinglePageAsync(final String resourceId, final QueryOptions queryOptions) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + Validator.validate(queryOptions); + final String apiVersion = "2019-07-01"; + Integer top = null; + if (queryOptions != null) { + top = queryOptions.top(); + } + String filter = null; + if (queryOptions != null) { + filter = queryOptions.filter(); + } + return service.listForResource(resourceId, apiVersion, this.client.acceptLanguage(), top, filter, this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listForResourceDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listForResourceDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Creates or updates a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner createOrUpdateAtResource(String resourceId, String remediationName, RemediationInner parameters) { + return createOrUpdateAtResourceWithServiceResponseAsync(resourceId, remediationName, parameters).toBlocking().single().body(); + } + + /** + * Creates or updates a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture createOrUpdateAtResourceAsync(String resourceId, String remediationName, RemediationInner parameters, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(createOrUpdateAtResourceWithServiceResponseAsync(resourceId, remediationName, parameters), serviceCallback); + } + + /** + * Creates or updates a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable createOrUpdateAtResourceAsync(String resourceId, String remediationName, RemediationInner parameters) { + return createOrUpdateAtResourceWithServiceResponseAsync(resourceId, remediationName, parameters).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Creates or updates a remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param parameters The remediation parameters. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> createOrUpdateAtResourceWithServiceResponseAsync(String resourceId, String remediationName, RemediationInner parameters) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + if (parameters == null) { + throw new IllegalArgumentException("Parameter parameters is required and cannot be null."); + } + Validator.validate(parameters); + final String apiVersion = "2019-07-01"; + return service.createOrUpdateAtResource(resourceId, remediationName, apiVersion, parameters, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = createOrUpdateAtResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse createOrUpdateAtResourceDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(201, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets an existing remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner getAtResource(String resourceId, String remediationName) { + return getAtResourceWithServiceResponseAsync(resourceId, remediationName).toBlocking().single().body(); + } + + /** + * Gets an existing remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture getAtResourceAsync(String resourceId, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(getAtResourceWithServiceResponseAsync(resourceId, remediationName), serviceCallback); + } + + /** + * Gets an existing remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable getAtResourceAsync(String resourceId, String remediationName) { + return getAtResourceWithServiceResponseAsync(resourceId, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Gets an existing remediation at resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> getAtResourceWithServiceResponseAsync(String resourceId, String remediationName) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + return service.getAtResource(resourceId, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = getAtResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse getAtResourceDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Deletes an existing remediation at individual resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @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 + * @return the RemediationInner object if successful. + */ + public RemediationInner deleteAtResource(String resourceId, String remediationName) { + return deleteAtResourceWithServiceResponseAsync(resourceId, remediationName).toBlocking().single().body(); + } + + /** + * Deletes an existing remediation at individual resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture deleteAtResourceAsync(String resourceId, String remediationName, final ServiceCallback serviceCallback) { + return ServiceFuture.fromResponse(deleteAtResourceWithServiceResponseAsync(resourceId, remediationName), serviceCallback); + } + + /** + * Deletes an existing remediation at individual resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable deleteAtResourceAsync(String resourceId, String remediationName) { + return deleteAtResourceWithServiceResponseAsync(resourceId, remediationName).map(new Func1, RemediationInner>() { + @Override + public RemediationInner call(ServiceResponse response) { + return response.body(); + } + }); + } + + /** + * Deletes an existing remediation at individual resource scope. + * + * @param resourceId Resource ID. + * @param remediationName The name of the remediation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the RemediationInner object + */ + public Observable> deleteAtResourceWithServiceResponseAsync(String resourceId, String remediationName) { + if (resourceId == null) { + throw new IllegalArgumentException("Parameter resourceId is required and cannot be null."); + } + if (remediationName == null) { + throw new IllegalArgumentException("Parameter remediationName is required and cannot be null."); + } + final String apiVersion = "2019-07-01"; + return service.deleteAtResource(resourceId, remediationName, apiVersion, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>() { + @Override + public Observable> call(Response response) { + try { + ServiceResponse clientResponse = deleteAtResourceDelegate(response); + return Observable.just(clientResponse); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse deleteAtResourceDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory().newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken() { }.getType()) + .register(204, new TypeToken() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtManagementGroupNext(final String nextPageLink) { + ServiceResponse> response = listDeploymentsAtManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtManagementGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtManagementGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtManagementGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtManagementGroupNextAsync(final String nextPageLink) { + return listDeploymentsAtManagementGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtManagementGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listDeploymentsAtManagementGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtManagementGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at management group scope. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtManagementGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listDeploymentsAtManagementGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtManagementGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDeploymentsAtManagementGroupNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all remediations for the management group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listForManagementGroupNext(final String nextPageLink) { + ServiceResponse> response = listForManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listForManagementGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for the management group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listForManagementGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listForManagementGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listForManagementGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for the management group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listForManagementGroupNextAsync(final String nextPageLink) { + return listForManagementGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for the management group. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listForManagementGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listForManagementGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listForManagementGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for the management group. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listForManagementGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listForManagementGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listForManagementGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listForManagementGroupNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtSubscriptionNext(final String nextPageLink) { + ServiceResponse> response = listDeploymentsAtSubscriptionNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtSubscriptionNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtSubscriptionNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtSubscriptionNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtSubscriptionNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtSubscriptionNextAsync(final String nextPageLink) { + return listDeploymentsAtSubscriptionNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtSubscriptionNextWithServiceResponseAsync(final String nextPageLink) { + return listDeploymentsAtSubscriptionNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtSubscriptionNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at subscription scope. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtSubscriptionNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listDeploymentsAtSubscriptionNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtSubscriptionNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDeploymentsAtSubscriptionNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all remediations for the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listNext(final String nextPageLink) { + ServiceResponse> response = listNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listNextAsync(final String nextPageLink) { + return listNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listNextWithServiceResponseAsync(final String nextPageLink) { + return listNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtResourceGroupNext(final String nextPageLink) { + ServiceResponse> response = listDeploymentsAtResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtResourceGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtResourceGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtResourceGroupNextAsync(final String nextPageLink) { + return listDeploymentsAtResourceGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtResourceGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listDeploymentsAtResourceGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at resource group scope. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtResourceGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listDeploymentsAtResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtResourceGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDeploymentsAtResourceGroupNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all remediations for the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listByResourceGroupNext(final String nextPageLink) { + ServiceResponse> response = listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listByResourceGroupNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listByResourceGroupNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listByResourceGroupNextAsync(final String nextPageLink) { + return listByResourceGroupNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listByResourceGroupNextWithServiceResponseAsync(final String nextPageLink) { + return listByResourceGroupNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listByResourceGroupNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for the subscription. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listByResourceGroupNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listByResourceGroupNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listByResourceGroupNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listByResourceGroupNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @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 + * @return the PagedList<RemediationDeploymentInner> object if successful. + */ + public PagedList listDeploymentsAtResourceNext(final String nextPageLink) { + ServiceResponse> response = listDeploymentsAtResourceNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listDeploymentsAtResourceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listDeploymentsAtResourceNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listDeploymentsAtResourceNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listDeploymentsAtResourceNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable> listDeploymentsAtResourceNextAsync(final String nextPageLink) { + return listDeploymentsAtResourceNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationDeploymentInner> object + */ + public Observable>> listDeploymentsAtResourceNextWithServiceResponseAsync(final String nextPageLink) { + return listDeploymentsAtResourceNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listDeploymentsAtResourceNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all deployments for a remediation at resource scope. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationDeploymentInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listDeploymentsAtResourceNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listDeploymentsAtResourceNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listDeploymentsAtResourceNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listDeploymentsAtResourceNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + + /** + * Gets all remediations for a resource. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @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 + * @return the PagedList<RemediationInner> object if successful. + */ + public PagedList listForResourceNext(final String nextPageLink) { + ServiceResponse> response = listForResourceNextSinglePageAsync(nextPageLink).toBlocking().single(); + return new PagedList(response.body()) { + @Override + public Page nextPage(String nextPageLink) { + return listForResourceNextSinglePageAsync(nextPageLink).toBlocking().single().body(); + } + }; + } + + /** + * Gets all remediations for a resource. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @param serviceFuture the ServiceFuture object tracking the Retrofit calls + * @param serviceCallback the async ServiceCallback to handle successful and failed responses. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the {@link ServiceFuture} object + */ + public ServiceFuture> listForResourceNextAsync(final String nextPageLink, final ServiceFuture> serviceFuture, final ListOperationCallback serviceCallback) { + return AzureServiceFuture.fromPageResponse( + listForResourceNextSinglePageAsync(nextPageLink), + new Func1>>>() { + @Override + public Observable>> call(String nextPageLink) { + return listForResourceNextSinglePageAsync(nextPageLink); + } + }, + serviceCallback); + } + + /** + * Gets all remediations for a resource. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable> listForResourceNextAsync(final String nextPageLink) { + return listForResourceNextWithServiceResponseAsync(nextPageLink) + .map(new Func1>, Page>() { + @Override + public Page call(ServiceResponse> response) { + return response.body(); + } + }); + } + + /** + * Gets all remediations for a resource. + * + * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the observable to the PagedList<RemediationInner> object + */ + public Observable>> listForResourceNextWithServiceResponseAsync(final String nextPageLink) { + return listForResourceNextSinglePageAsync(nextPageLink) + .concatMap(new Func1>, Observable>>>() { + @Override + public Observable>> call(ServiceResponse> page) { + String nextPageLink = page.body().nextPageLink(); + if (nextPageLink == null) { + return Observable.just(page); + } + return Observable.just(page).concatWith(listForResourceNextWithServiceResponseAsync(nextPageLink)); + } + }); + } + + /** + * Gets all remediations for a resource. + * + ServiceResponse> * @param nextPageLink The NextLink from the previous successful call to List operation. + * @throws IllegalArgumentException thrown if parameters fail the validation + * @return the PagedList<RemediationInner> object wrapped in {@link ServiceResponse} if successful. + */ + public Observable>> listForResourceNextSinglePageAsync(final String nextPageLink) { + if (nextPageLink == null) { + throw new IllegalArgumentException("Parameter nextPageLink is required and cannot be null."); + } + String nextUrl = String.format("%s", nextPageLink); + return service.listForResourceNext(nextUrl, this.client.acceptLanguage(), this.client.userAgent()) + .flatMap(new Func1, Observable>>>() { + @Override + public Observable>> call(Response response) { + try { + ServiceResponse> result = listForResourceNextDelegate(response); + return Observable.just(new ServiceResponse>(result.body(), result.response())); + } catch (Throwable t) { + return Observable.error(t); + } + } + }); + } + + private ServiceResponse> listForResourceNextDelegate(Response response) throws ErrorResponseException, IOException, IllegalArgumentException { + return this.client.restClient().responseBuilderFactory()., ErrorResponseException>newInstance(this.client.serializerAdapter()) + .register(200, new TypeToken>() { }.getType()) + .registerError(ErrorResponseException.class) + .build(response); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SlimPolicyMetadataImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SlimPolicyMetadataImpl.java new file mode 100644 index 0000000000000..bbd1ff60be990 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SlimPolicyMetadataImpl.java @@ -0,0 +1,71 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.SlimPolicyMetadata; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; + +class SlimPolicyMetadataImpl extends WrapperImpl implements SlimPolicyMetadata { + private final PolicyInsightsManager manager; + SlimPolicyMetadataImpl(SlimPolicyMetadataInner inner, PolicyInsightsManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public String additionalContentUrl() { + return this.inner().additionalContentUrl(); + } + + @Override + public String category() { + return this.inner().category(); + } + + @Override + public String id() { + return this.inner().id(); + } + + @Override + public Object metadata() { + return this.inner().metadata(); + } + + @Override + public String metadataId() { + return this.inner().metadataId(); + } + + @Override + public String name() { + return this.inner().name(); + } + + @Override + public String owner() { + return this.inner().owner(); + } + + @Override + public String title() { + return this.inner().title(); + } + + @Override + public String type() { + return this.inner().type(); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SlimPolicyMetadataInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SlimPolicyMetadataInner.java new file mode 100644 index 0000000000000..94fe380ac6a11 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SlimPolicyMetadataInner.java @@ -0,0 +1,155 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.fasterxml.jackson.annotation.JsonProperty; +import com.microsoft.rest.serializer.JsonFlatten; + +/** + * Slim version of policy metadata resource definition, excluding properties + * with large strings. + */ +@JsonFlatten +public class SlimPolicyMetadataInner { + /** + * The policy metadata identifier. + */ + @JsonProperty(value = "properties.metadataId", access = JsonProperty.Access.WRITE_ONLY) + private String metadataId; + + /** + * The category of the policy metadata. + */ + @JsonProperty(value = "properties.category", access = JsonProperty.Access.WRITE_ONLY) + private String category; + + /** + * The title of the policy metadata. + */ + @JsonProperty(value = "properties.title", access = JsonProperty.Access.WRITE_ONLY) + private String title; + + /** + * The owner of the policy metadata. + */ + @JsonProperty(value = "properties.owner", access = JsonProperty.Access.WRITE_ONLY) + private String owner; + + /** + * Url for getting additional content about the resource metadata. + */ + @JsonProperty(value = "properties.additionalContentUrl", access = JsonProperty.Access.WRITE_ONLY) + private String additionalContentUrl; + + /** + * Additional metadata. + */ + @JsonProperty(value = "properties.metadata", access = JsonProperty.Access.WRITE_ONLY) + private Object metadata; + + /** + * The ID of the policy metadata. + */ + @JsonProperty(value = "id", access = JsonProperty.Access.WRITE_ONLY) + private String id; + + /** + * The type of the policy metadata. + */ + @JsonProperty(value = "type", access = JsonProperty.Access.WRITE_ONLY) + private String type; + + /** + * The name of the policy metadata. + */ + @JsonProperty(value = "name", access = JsonProperty.Access.WRITE_ONLY) + private String name; + + /** + * Get the policy metadata identifier. + * + * @return the metadataId value + */ + public String metadataId() { + return this.metadataId; + } + + /** + * Get the category of the policy metadata. + * + * @return the category value + */ + public String category() { + return this.category; + } + + /** + * Get the title of the policy metadata. + * + * @return the title value + */ + public String title() { + return this.title; + } + + /** + * Get the owner of the policy metadata. + * + * @return the owner value + */ + public String owner() { + return this.owner; + } + + /** + * Get url for getting additional content about the resource metadata. + * + * @return the additionalContentUrl value + */ + public String additionalContentUrl() { + return this.additionalContentUrl; + } + + /** + * Get additional metadata. + * + * @return the metadata value + */ + public Object metadata() { + return this.metadata; + } + + /** + * Get the ID of the policy metadata. + * + * @return the id value + */ + public String id() { + return this.id; + } + + /** + * Get the type of the policy metadata. + * + * @return the type value + */ + public String type() { + return this.type; + } + + /** + * Get the name of the policy metadata. + * + * @return the name value + */ + public String name() { + return this.name; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SummarizeResultsImpl.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SummarizeResultsImpl.java new file mode 100644 index 0000000000000..41c8e59431874 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SummarizeResultsImpl.java @@ -0,0 +1,43 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import com.microsoft.azure.management.policyinsights.v2019_10_01.SummarizeResults; +import com.microsoft.azure.arm.model.implementation.WrapperImpl; +import java.util.List; +import com.microsoft.azure.management.policyinsights.v2019_10_01.Summary; + +class SummarizeResultsImpl extends WrapperImpl implements SummarizeResults { + private final PolicyInsightsManager manager; + SummarizeResultsImpl(SummarizeResultsInner inner, PolicyInsightsManager manager) { + super(inner); + this.manager = manager; + } + + @Override + public PolicyInsightsManager manager() { + return this.manager; + } + + @Override + public String odatacontext() { + return this.inner().odatacontext(); + } + + @Override + public Integer odatacount() { + return this.inner().odatacount(); + } + + @Override + public List value() { + return this.inner().value(); + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SummarizeResultsInner.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SummarizeResultsInner.java new file mode 100644 index 0000000000000..1787d03d6b8a2 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/SummarizeResultsInner.java @@ -0,0 +1,99 @@ +/** + * Copyright (c) Microsoft Corporation. All rights reserved. + * Licensed under the MIT License. See License.txt in the project root for + * license information. + * + * Code generated by Microsoft (R) AutoRest Code Generator. + */ + +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; + +import java.util.List; +import com.microsoft.azure.management.policyinsights.v2019_10_01.Summary; +import com.fasterxml.jackson.annotation.JsonProperty; + +/** + * Summarize action results. + */ +public class SummarizeResultsInner { + /** + * OData context string; used by OData clients to resolve type information + * based on metadata. + */ + @JsonProperty(value = "@odata\\.context") + private String odatacontext; + + /** + * OData entity count; represents the number of summaries returned; always + * set to 1. + */ + @JsonProperty(value = "@odata\\.count") + private Integer odatacount; + + /** + * Summarize action results. + */ + @JsonProperty(value = "value") + private List value; + + /** + * Get oData context string; used by OData clients to resolve type information based on metadata. + * + * @return the odatacontext value + */ + public String odatacontext() { + return this.odatacontext; + } + + /** + * Set oData context string; used by OData clients to resolve type information based on metadata. + * + * @param odatacontext the odatacontext value to set + * @return the SummarizeResultsInner object itself. + */ + public SummarizeResultsInner withOdatacontext(String odatacontext) { + this.odatacontext = odatacontext; + return this; + } + + /** + * Get oData entity count; represents the number of summaries returned; always set to 1. + * + * @return the odatacount value + */ + public Integer odatacount() { + return this.odatacount; + } + + /** + * Set oData entity count; represents the number of summaries returned; always set to 1. + * + * @param odatacount the odatacount value to set + * @return the SummarizeResultsInner object itself. + */ + public SummarizeResultsInner withOdatacount(Integer odatacount) { + this.odatacount = odatacount; + return this; + } + + /** + * Get summarize action results. + * + * @return the value value + */ + public List value() { + return this.value; + } + + /** + * Set summarize action results. + * + * @param value the value value to set + * @return the SummarizeResultsInner object itself. + */ + public SummarizeResultsInner withValue(List value) { + this.value = value; + return this; + } + +} diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/package-info.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/package-info.java new file mode 100644 index 0000000000000..35863d57b28a9 --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/implementation/package-info.java @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the implementation classes for PolicyInsightsClient. + */ +package com.microsoft.azure.management.policyinsights.v2019_10_01.implementation; diff --git a/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/package-info.java b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/package-info.java new file mode 100644 index 0000000000000..171e3aac7860a --- /dev/null +++ b/sdk/policyinsights/mgmt-v2019_10_01/src/main/java/com/microsoft/azure/management/policyinsights/v2019_10_01/package-info.java @@ -0,0 +1,10 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. See License.txt in the project root for +// license information. +// +// Code generated by Microsoft (R) AutoRest Code Generator. + +/** + * This package contains the classes for PolicyInsightsClient. + */ +package com.microsoft.azure.management.policyinsights.v2019_10_01; diff --git a/sdk/policyinsights/pom.mgmt.xml b/sdk/policyinsights/pom.mgmt.xml index c2c9d9f7f2c9c..e490954706bae 100644 --- a/sdk/policyinsights/pom.mgmt.xml +++ b/sdk/policyinsights/pom.mgmt.xml @@ -11,5 +11,6 @@ mgmt-v2018_04_04 mgmt-v2018_07_01_preview + mgmt-v2019_10_01 diff --git a/sdk/servicebus/microsoft-azure-servicebus/pom.xml b/sdk/servicebus/microsoft-azure-servicebus/pom.xml index ddf4c9c9c1475..b2d3bf16a9397 100644 --- a/sdk/servicebus/microsoft-azure-servicebus/pom.xml +++ b/sdk/servicebus/microsoft-azure-servicebus/pom.xml @@ -78,7 +78,7 @@ com.microsoft.azure azure-client-authentication - 1.6.7 + 1.7.0 compile diff --git a/sdk/spring/ci.yml b/sdk/spring/ci.yml new file mode 100644 index 0000000000000..af34bb9f3b791 --- /dev/null +++ b/sdk/spring/ci.yml @@ -0,0 +1,43 @@ +# DO NOT EDIT THIS FILE +# This file is generated automatically and any changes will be lost. + +resources: + repositories: + - repository: azure-sdk-build-tools + type: git + name: internal/azure-sdk-build-tools + - repository: azure-sdk-tools + type: github + name: Azure/azure-sdk-tools + endpoint: azure + +trigger: + branches: + include: + - master + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/spring/ + +pr: + branches: + include: + - master + - feature/* + - hotfix/* + - release/* + paths: + include: + - sdk/spring/ + +stages: + - template: ../../eng/pipelines/templates/stages/archetype-sdk-client.yml + parameters: + ServiceDirectory: spring + Artifacts: + - name: azure-spring-something + safeName: azurespringsomething + stagingProfileId: 88192f04117501 \ No newline at end of file diff --git a/sdk/storage/azure-storage-blob-batch/CHANGELOG.md b/sdk/storage/azure-storage-blob-batch/CHANGELOG.md index 3db2ff62b2c7a..d6894157673ec 100644 --- a/sdk/storage/azure-storage-blob-batch/CHANGELOG.md +++ b/sdk/storage/azure-storage-blob-batch/CHANGELOG.md @@ -1,6 +1,12 @@ # Release History -## 12.2.0-beta.1 (Unreleased) +## 12.2.0 (2020-01-08) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-blob-batch_12.2.0/sdk/storage/azure-storage-blob-batch/README.md) +and +[samples](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-blob-batch_12.2.0/sdk/storage/azure-storage-blob-batch/src/samples/java/com/azure/storage/blob/batch) + +- Upgraded to version 12.2.0 of Azure Storage Blob. ## 12.1.0 (2019-12-04) This package's diff --git a/sdk/storage/azure-storage-blob-batch/README.md b/sdk/storage/azure-storage-blob-batch/README.md index 551b0e04f6239..c80971f5dd49a 100644 --- a/sdk/storage/azure-storage-blob-batch/README.md +++ b/sdk/storage/azure-storage-blob-batch/README.md @@ -22,7 +22,7 @@ definition, such as text or binary data. com.azure azure-storage-blob-batch - 12.1.0 + 12.2.0 ``` [//]: # ({x-version-update-end}) @@ -41,7 +41,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-storage-blob-batch - 12.1.0 + 12.2.0 com.azure diff --git a/sdk/storage/azure-storage-blob-batch/pom.xml b/sdk/storage/azure-storage-blob-batch/pom.xml index 5c832199c9e4c..209d9baa5e319 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.2.0-beta.1 + 12.2.0 Microsoft Azure client library for Blob Storage batching This module contains client library for Microsoft Azure Blob Storage batching. @@ -55,17 +55,17 @@ com.azure azure-core - 1.1.0 + 1.2.0 com.azure azure-core-http-netty - 1.1.0 + 1.2.0 com.azure azure-storage-blob - 12.2.0-beta.2 + 12.2.0 org.slf4j @@ -86,13 +86,13 @@ com.azure azure-core-test - 1.1.0-beta.2 + 1.1.0 test com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/storage/azure-storage-blob-batch/src/test/java/com/azure/storage/blob/batch/APISpec.groovy b/sdk/storage/azure-storage-blob-batch/src/test/java/com/azure/storage/blob/batch/APISpec.groovy index 73bd51cc2e884..25715cb1cdeb5 100644 --- a/sdk/storage/azure-storage-blob-batch/src/test/java/com/azure/storage/blob/batch/APISpec.groovy +++ b/sdk/storage/azure-storage-blob-batch/src/test/java/com/azure/storage/blob/batch/APISpec.groovy @@ -98,6 +98,9 @@ class APISpec extends Specification { this.interceptorManager = new InterceptorManager(className + fullTestName, testMode) this.resourceNamer = new TestResourceNamer(className + testName, testMode, interceptorManager.getRecordedData()) + // Print out the test name to create breadcrumbs in our test logging in case anything hangs. + System.out.printf("========================= %s.%s =========================%n", className, fullTestName) + // If the test doesn't have the Requires tag record it in live mode. recordLiveMode = specificationContext.getCurrentIteration().getDescription().getAnnotation(Requires.class) == null diff --git a/sdk/storage/azure-storage-blob-cryptography/CHANGELOG.md b/sdk/storage/azure-storage-blob-cryptography/CHANGELOG.md index 02268d9165595..322465abc6415 100644 --- a/sdk/storage/azure-storage-blob-cryptography/CHANGELOG.md +++ b/sdk/storage/azure-storage-blob-cryptography/CHANGELOG.md @@ -1,6 +1,12 @@ # Release History -## 12.2.0-beta.1 (Unreleased) +## 12.2.0 (2020-01-08) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-blob-cryptography_12.2.0/sdk/storage/azure-storage-blob-cryptography/README.md) +and +[samples](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-blob-cryptography_12.2.0/sdk/storage/azure-storage-blob-cryptography/src/samples/java/com/azure/storage/blob/cryptography) + +- Upgraded to version 12.2.0 of Azure Storage Blob. ## 12.1.0 (2019-12-04) This package's diff --git a/sdk/storage/azure-storage-blob-cryptography/README.md b/sdk/storage/azure-storage-blob-cryptography/README.md index bf82d86818e9f..2071676104443 100644 --- a/sdk/storage/azure-storage-blob-cryptography/README.md +++ b/sdk/storage/azure-storage-blob-cryptography/README.md @@ -21,7 +21,7 @@ This package supports client side encryption for blob storage. com.azure azure-storage-blob-cryptography - 12.1.0 + 12.2.0 ``` [//]: # ({x-version-update-end}) @@ -40,7 +40,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-storage-blob - 12.1.0 + 12.2.0 com.azure diff --git a/sdk/storage/azure-storage-blob-cryptography/pom.xml b/sdk/storage/azure-storage-blob-cryptography/pom.xml index 99992896009c2..ea31b4fa7408a 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.2.0-beta.1 + 12.2.0 Microsoft Azure client library for Blob Storage cryptography This module contains client library for Microsoft Azure Blob Storage cryptography. @@ -36,18 +36,18 @@ com.azure azure-storage-blob - 12.2.0-beta.2 + 12.2.0 com.azure azure-core-test - 1.1.0-beta.2 + 1.1.0 test com.azure azure-core-http-netty - 1.1.0 + 1.2.0 test @@ -92,7 +92,7 @@ com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/storage/azure-storage-blob-cryptography/src/test/java/com/azure/storage/blob/specialized/cryptography/APISpec.groovy b/sdk/storage/azure-storage-blob-cryptography/src/test/java/com/azure/storage/blob/specialized/cryptography/APISpec.groovy index e50e3ad98cfac..c52685549cba8 100644 --- a/sdk/storage/azure-storage-blob-cryptography/src/test/java/com/azure/storage/blob/specialized/cryptography/APISpec.groovy +++ b/sdk/storage/azure-storage-blob-cryptography/src/test/java/com/azure/storage/blob/specialized/cryptography/APISpec.groovy @@ -114,6 +114,10 @@ class APISpec extends Specification { this.testName = fullTestName.substring(0, substringIndex) this.interceptorManager = new InterceptorManager(className + fullTestName, testMode) this.resourceNamer = new TestResourceNamer(className + testName, testMode, interceptorManager.getRecordedData()) + + // Print out the test name to create breadcrumbs in our test logging in case anything hangs. + System.out.printf("========================= %s.%s =========================%n", className, fullTestName) + // If the test doesn't have the Requires tag record it in live mode. recordLiveMode = specificationContext.getCurrentIteration().getDescription().getAnnotation(Requires.class) == null connectionString = Configuration.getGlobalConfiguration().get("AZURE_STORAGE_BLOB_CONNECTION_STRING") diff --git a/sdk/storage/azure-storage-blob-nio/CHANGELOG.md b/sdk/storage/azure-storage-blob-nio/CHANGELOG.md new file mode 100644 index 0000000000000..972764e38a67d --- /dev/null +++ b/sdk/storage/azure-storage-blob-nio/CHANGELOG.md @@ -0,0 +1,10 @@ +# Release History + +This package's +[documentation](LINK) +and +[samples](LINK) +demonstrate the new API. + +## 12.0.0-beta.1 (Unreleased) +- Initial Release. Please see the README and wiki for information on the new design. diff --git a/sdk/storage/azure-storage-blob-nio/README.md b/sdk/storage/azure-storage-blob-nio/README.md new file mode 100644 index 0000000000000..b23502f9c1bd9 --- /dev/null +++ b/sdk/storage/azure-storage-blob-nio/README.md @@ -0,0 +1,215 @@ +# Azure Storage Blob implementation of Java NIO +## This README is not yet updated for this project and is a skeleton copied from blobs + +[Source code][source] | [API reference documentation][docs] | [REST API documentation][rest_docs] | [Product documentation][product_docs] | [Samples][samples] + +## Getting started + +### Prerequisites + +- [Java Development Kit (JDK)][jdk] with version 8 or above +- [Azure Subscription][azure_subscription] +- [Create Storage Account][storage_account] + +### Adding the package to your product + +[//]: # ({x-version-update-start;com.azure:azure-storage-blob-nio;current}) +```xml + + com.azure + azure-storage-blob-nio + 12.0.0-beta.1 + +``` +[//]: # ({x-version-update-end}) + +### Default HTTP Client +All client libraries, by default, use the Netty HTTP client. Adding the above dependency will automatically configure +Storage Blob to use the Netty HTTP client. + +### Alternate HTTP client +If, instead of Netty it is preferable to use OkHTTP, there is an HTTP client available for that too. Exclude the default +Netty and include the OkHTTP client in your pom.xml. + +[//]: # ({x-version-update-start;com.azure:azure-storage-blob;current}) +```xml + + + com.azure + azure-storage-blob + 12.2.0 + + + com.azure + azure-core-http-netty + + + +``` +[//]: # ({x-version-update-end}) +[//]: # ({x-version-update-start;com.azure:azure-core-http-okhttp;current}) +```xml + + + com.azure + azure-core-http-okhttp + 1.1.0 + +``` +[//]: # ({x-version-update-end}) + +### Configuring HTTP Clients +When an HTTP client is included on the classpath, as shown above, it is not necessary to specify it in the client library [builders](#create-blobserviceclient) unless you want to customize the HTTP client in some fashion. If this is desired, the `httpClient` builder method is often available to achieve just this by allowing users to provide custom (or customized) `com.azure.core.http.HttpClient` instances. + +For starters, by having the Netty or OkHTTP dependencies on your classpath, as shown above, you can create new instances of these `HttpClient` types using their builder APIs. For example, here is how you would create a Netty HttpClient instance: + +### Default SSL library +All client libraries, by default, use the Tomcat-native Boring SSL library to enable native-level performance for SSL operations. The Boring SSL library is an uber jar containing native libraries for Linux / macOS / Windows, and provides better performance compared to the default SSL implementation within the JDK. For more information, including how to reduce the dependency size, refer to the [performance tuning][performance_tuning] section of the wiki. + +```java +HttpClient client = new NettyAsyncHttpClientBuilder() + .port(8080) + .wiretap(true) + .build(); +``` + +### Create a Storage Account +To create a Storage Account you can use the [Azure Portal][storage_account_create_portal] or [Azure CLI][storage_account_create_cli]. + +```bash +az storage account create \ + --resource-group \ + --name \ + --location +``` + +### Authenticate the client + +In order to interact with the Storage Service (Blob, Queue, Message, MessageId, File) you'll need to create an instance of the Service Client class. +To make this possible you'll need the Account SAS (shared access signature) string of the Storage Account. Learn more at [SAS Token][sas_token] + +#### Get credentials + +##### SAS Token + +a. Use the Azure CLI snippet below to get the SAS token from the Storage Account. + +```bash +az storage blob generate-sas \ + --account-name {Storage Account name} \ + --container-name {container name} \ + --name {blob name} \ + --permissions {permissions to grant} \ + --expiry {datetime to expire the SAS token} \ + --services {storage services the SAS allows} \ + --resource-types {resource types the SAS allows} +``` + +Example: + +```bash +CONNECTION_STRING= + +az storage blob generate-sas \ + --account-name MyStorageAccount \ + --container-name MyContainer \ + --name MyBlob \ + --permissions racdw \ + --expiry 2020-06-15 +``` + +b. Alternatively, get the Account SAS Token from the Azure Portal. + +1. Go to your Storage Account +2. Select `Shared access signature` from the menu on the left +3. Click on `Generate SAS and connection string` (after setup) + +##### **Shared Key Credential** + +a. Use Account name and Account key. Account name is your Storage Account name. + +1. Go to your Storage Account +2. Select `Access keys` from the menu on the left +3. Under `key1`/`key2` copy the contents of the `Key` field + +or + +b. Use the connection string. + +1. Go to your Storage Account +2. Select `Access keys` from the menu on the left +3. Under `key1`/`key2` copy the contents of the `Connection string` field + +## Key concepts + +Blob Storage is designed for: + +- Serving images or documents directly to a browser +- Storing files for distributed access +- Streaming video and audio +- Writing to log files +- Storing data for backup and restore, disaster recovery, and archiving +- Storing data for analysis by an on-premises or Azure-hosted service + +## Examples + +The following sections provide several code snippets covering some of the most common Azure Storage Blob tasks, including: + +- [Create a `BlobServiceClient`](#create-a-blobserviceclient) + + +### Create a `BlobServiceClient` + +Create a `BlobServiceClient` using the [`sasToken`](#get-credentials) generated above. + +```java +BlobServiceClient blobServiceClient = new BlobServiceClientBuilder() + .endpoint("") + .sasToken("") + .buildClient(); +``` + + +## Troubleshooting + +When interacting with blobs using this Java client library, errors returned by the service correspond to the same HTTP +status codes returned for [REST API][error_codes] requests. For example, if you try to retrieve a container or blob that +doesn't exist in your Storage Account, a `404` error is returned, indicating `Not Found`. + +## Next steps + +Several Storage blob Java SDK samples are available to you in the SDK's GitHub repository. These samples provide example code for additional scenarios commonly encountered while working with Key Vault: + +## Next steps Samples +Samples are explained in detail [here][samples_readme]. + +## Contributing + +This project welcomes contributions and suggestions. Most contributions require you to agree to a [Contributor License Agreement (CLA)][cla] declaring that you have the right to, and actually do, grant us the rights to use your contribution. + +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][coc]. For more information see the [Code of Conduct FAQ][coc_faq] or contact [opencode@microsoft.com][coc_contact] with any additional questions or comments. + + +[source]: src +[samples_readme]: src/samples/README.md +[docs]: http://azure.github.io/azure-sdk-for-java/ +[rest_docs]: https://docs.microsoft.com/rest/api/storageservices/blob-service-rest-api +[product_docs]: https://docs.microsoft.com/azure/storage/blobs/storage-blobs-overview +[sas_token]: https://docs.microsoft.com/azure/storage/common/storage-dotnet-shared-access-signature-part-1 +[jdk]: https://docs.microsoft.com/java/azure/jdk/ +[azure_subscription]: https://azure.microsoft.com/free/ +[storage_account]: https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-portal +[storage_account_create_cli]: https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-cli +[storage_account_create_portal]: https://docs.microsoft.com/azure/storage/common/storage-quickstart-create-account?tabs=azure-portal +[identity]: https://github.com/Azure/azure-sdk-for-java/blob/master/sdk/identity/azure-identity/README.md +[error_codes]: https://docs.microsoft.com/rest/api/storageservices/blob-service-error-codes +[samples]: src/samples +[cla]: https://cla.microsoft.com +[coc]: https://opensource.microsoft.com/codeofconduct/ +[coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ +[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-nio/pom.xml b/sdk/storage/azure-storage-blob-nio/pom.xml new file mode 100644 index 0000000000000..49f70c1da6d0c --- /dev/null +++ b/sdk/storage/azure-storage-blob-nio/pom.xml @@ -0,0 +1,269 @@ + + + + com.azure + azure-client-sdk-parent + 1.7.0 + ../../../pom.client.xml + + + 4.0.0 + + com.azure + azure-storage-blob-nio + 12.0.0-beta.1 + + 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 + + + + azure-java-build-docs + ${site.url}/site/${project.artifactId} + + + + + scm:git:https://github.com/Azure/azure-sdk-for-java + scm:git:git@github.com:Azure/azure-sdk-for-java.git + HEAD + + + + src/main/java + src/test/java + + + + + bintray + Groovy Bintray + https://dl.bintray.com/groovy/maven + + never + + + false + + + + + + + com.azure + azure-storage-blob + 12.2.0-beta.1 + + + org.slf4j + slf4j-api + 1.7.28 + + + + com.azure + azure-core-test + 1.1.0 + test + + + com.azure + azure-core-http-netty + 1.2.0 + test + + + com.azure + azure-identity + 1.0.2 + test + + + org.slf4j + slf4j-simple + 1.7.25 + test + + + io.projectreactor + reactor-test + 3.3.0.RELEASE + test + + + com.microsoft.azure + adal4j + 1.6.4 + test + + + org.spockframework + spock-core + 1.3-groovy-2.5 + test + + + cglib + cglib-nodep + 3.2.7 + test + + + + + src/main/java + src/test/java + + + ${basedir}/src/test/resources + + + + + + + java8 + + [1.8,9) + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 1.8 + 1.8 + true + true + + -Xlint:all + -Xlint:-serial + -Xlint:-deprecation + -Xlint:-processing + + + module-info.java + + + + + + test-compile + process-test-sources + + testCompile + + + groovy-eclipse-compiler + -warn:-unused + + + + default-testCompile + process-test-sources + + testCompile + + + groovy-eclipse-compiler + -warn:-unused + + + + + + org.codehaus.groovy + groovy-eclipse-compiler + 3.4.0-01 + + + org.codehaus.groovy + groovy-eclipse-batch + 2.5.8-01 + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M3 + + + + + + + java9plus + + [9,) + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.1 + + 9 + 9 + + + + test-compile + process-test-sources + + testCompile + + + groovy-eclipse-compiler + -warn:-unused + 8 + + + + default-testCompile + process-test-sources + + testCompile + + + groovy-eclipse-compiler + -warn:-unused + 8 + + + + + + org.codehaus.groovy + groovy-eclipse-compiler + 3.4.0-01 + + + org.codehaus.groovy + groovy-eclipse-batch + 2.5.8-01 + + + + + + org.apache.maven.plugins + maven-surefire-plugin + 3.0.0-M3 + + + + + + + + + + diff --git a/sdk/storage/azure-storage-blob-nio/src/main/java/com/azure/storage/blob/nio/AzureFileSystemProvider.java b/sdk/storage/azure-storage-blob-nio/src/main/java/com/azure/storage/blob/nio/AzureFileSystemProvider.java new file mode 100644 index 0000000000000..72e5dd611c694 --- /dev/null +++ b/sdk/storage/azure-storage-blob-nio/src/main/java/com/azure/storage/blob/nio/AzureFileSystemProvider.java @@ -0,0 +1,11 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.storage.blob.nio; + +/** + * Empty class. + */ +public class AzureFileSystemProvider { + +} diff --git a/sdk/storage/azure-storage-blob-nio/src/main/java/com/azure/storage/blob/nio/package-info.java b/sdk/storage/azure-storage-blob-nio/src/main/java/com/azure/storage/blob/nio/package-info.java new file mode 100644 index 0000000000000..96cd1fbd62756 --- /dev/null +++ b/sdk/storage/azure-storage-blob-nio/src/main/java/com/azure/storage/blob/nio/package-info.java @@ -0,0 +1,7 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +/** + * Package containing the classes for loading the AzureFileSystemProvider based on Azure Storage Blobs. + */ +package com.azure.storage.blob.nio; diff --git a/sdk/storage/azure-storage-blob-nio/src/main/java/module-info.java b/sdk/storage/azure-storage-blob-nio/src/main/java/module-info.java new file mode 100644 index 0000000000000..58d95ad8f3060 --- /dev/null +++ b/sdk/storage/azure-storage-blob-nio/src/main/java/module-info.java @@ -0,0 +1,15 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +module com.azure.storage.blob.nio { + requires transitive com.azure.core; + requires transitive com.azure.storage.common; + requires com.azure.storage.blob; + requires com.fasterxml.jackson.dataformat.xml; + + exports com.azure.storage.blob.nio; + + opens com.azure.storage.blob.nio to + com.fasterxml.jackson.databind, + com.azure.core; +} diff --git a/sdk/storage/azure-storage-blob-nio/src/main/resources/META_INF/services/java.nio.file.spi.FileSystemProvider b/sdk/storage/azure-storage-blob-nio/src/main/resources/META_INF/services/java.nio.file.spi.FileSystemProvider new file mode 100644 index 0000000000000..7d26d6d7a2f97 --- /dev/null +++ b/sdk/storage/azure-storage-blob-nio/src/main/resources/META_INF/services/java.nio.file.spi.FileSystemProvider @@ -0,0 +1 @@ +main.java.com.azure.storage.nio.blob.AzureFileSystemProvider \ No newline at end of file diff --git a/sdk/storage/azure-storage-blob/CHANGELOG.md b/sdk/storage/azure-storage-blob/CHANGELOG.md index 25f6ac6ba88ea..7f20b8a355246 100644 --- a/sdk/storage/azure-storage-blob/CHANGELOG.md +++ b/sdk/storage/azure-storage-blob/CHANGELOG.md @@ -1,12 +1,22 @@ # Release History -## 12.2.0-beta.2 (Unreleased) -- Added a field to ParallelTransferOptions that allows customers to configure the maximum size to upload in a single PUT. Data sizes larger than this value will be chunked and parallelized. +## 12.3.0-beta.1 (Unreleased) - Added support for the 2019-07-07 service version. - Added support for encryption scopes service, container and blob builders now accept an encryption scope parameter and service and container builders accept a BlobContainerEncryptionScope parameter. - Added support for managed disk page range diff for managed disk accounts +## 12.2.0 (2020-01-08) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-blob_12.2.0/sdk/storage/azure-storage-blob/README.md) +and +[samples](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-blob_12.2.0/sdk/storage/azure-storage-blob/src/samples/java/com/azure/storage/blob) + +- Added a field to ParallelTransferOptions that allows customers to configure the maximum size to upload in a single PUT. Data sizes larger than this value will be chunked and parallelized. +- Added overloads to downloadToFile to add the option to overwrite existing files. Default behavior is to not overwrite. +- Improved performance of BlockBlobOutputStream. +- Added overloads to BlockBlobClient.getBlobOutputStream to allow users to provide parallel transfer options, http headers, metadata, access tier, and request conditions. + ## 12.2.0-beta.1 (2019-12-17) - Added SAS generation methods on clients to improve discoverability and convenience of sas. Deprecated setContainerName, setBlobName, setSnapshotId, generateSasQueryParameters methods on BlobServiceSasSignatureValues to direct users to using the methods added on clients. - Fixed a bug where Account SAS would not work when set on clients. diff --git a/sdk/storage/azure-storage-blob/README.md b/sdk/storage/azure-storage-blob/README.md index 41b9c0cbca058..6339cf47634d7 100644 --- a/sdk/storage/azure-storage-blob/README.md +++ b/sdk/storage/azure-storage-blob/README.md @@ -22,7 +22,7 @@ definition, such as text or binary data. com.azure azure-storage-blob - 12.2.0-beta.2 + 12.2.0 ``` [//]: # ({x-version-update-end}) @@ -41,7 +41,7 @@ Netty and include the OkHTTP client in your pom.xml. com.azure azure-storage-blob - 12.2.0-beta.2 + 12.2.0 com.azure diff --git a/sdk/storage/azure-storage-blob/pom.xml b/sdk/storage/azure-storage-blob/pom.xml index ee71483c14079..e1caa626a8b77 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.2.0-beta.2 + 12.2.0 Microsoft Azure client library for Blob Storage This module contains client library for Microsoft Azure Blob Storage. @@ -55,12 +55,12 @@ com.azure azure-core - 1.1.0 + 1.2.0 com.azure azure-storage-common - 12.2.0-beta.2 + 12.2.0 org.slf4j @@ -81,19 +81,19 @@ com.azure azure-core-test - 1.1.0-beta.2 + 1.1.0 test com.azure azure-core-http-netty - 1.1.0 + 1.2.0 test com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobAsyncClientBase.java b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobAsyncClientBase.java index edeceab91b2b5..64e4a880e815b 100644 --- a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobAsyncClientBase.java +++ b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobAsyncClientBase.java @@ -66,11 +66,14 @@ import java.nio.channels.AsynchronousFileChannel; import java.nio.file.FileAlreadyExistsException; import java.nio.file.Files; +import java.nio.file.OpenOption; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.time.Duration; import java.time.OffsetDateTime; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; @@ -713,8 +716,42 @@ private Mono downloadHelper(BlobRange range, DownloadRetryOpti * @return A reactive response containing the blob properties and metadata. */ public Mono downloadToFile(String filePath) { + return downloadToFile(filePath, false); + } + + /** + * Downloads the entire blob into a file specified by the path. + * + *

If overwrite is set to false, the file will be created and must not exist, if the file already exists a + * {@link FileAlreadyExistsException} will be thrown.

+ * + *

Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link + * AppendBlobClient}.

+ * + *

Code Samples

+ * + * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFile#String-boolean} + * + *

For more information, see the + * Azure Docs

+ * + * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. + * @param overwrite Whether or not to overwrite the file, should the file exist. + * @return A reactive response containing the blob properties and metadata. + */ + public Mono downloadToFile(String filePath, boolean overwrite) { try { - return downloadToFileWithResponse(filePath, null, null, null, null, false).flatMap(FluxUtil::toMono); + Set openOptions = null; + if (overwrite) { + openOptions = new HashSet<>(); + openOptions.add(StandardOpenOption.CREATE); + openOptions.add(StandardOpenOption.TRUNCATE_EXISTING); // If the file already exists and it is opened + // for WRITE access, then its length is truncated to 0. + openOptions.add(StandardOpenOption.READ); + openOptions.add(StandardOpenOption.WRITE); + } + return downloadToFileWithResponse(filePath, null, null, null, null, false, openOptions) + .flatMap(FluxUtil::toMono); } catch (RuntimeException ex) { return monoError(logger, ex); } @@ -753,9 +790,48 @@ public Mono downloadToFile(String filePath) { public Mono> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions options, BlobRequestConditions requestConditions, boolean rangeGetContentMd5) { + return downloadToFileWithResponse(filePath, range, parallelTransferOptions, options, requestConditions, + rangeGetContentMd5, null); + } + + /** + * Downloads the entire blob into a file specified by the path. + * + *

By default the file will be created and must not exist, if the file already exists a + * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate + * {@link OpenOption OpenOptions}

+ * + *

Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link + * AppendBlobClient}.

+ * + *

This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra + * call, provide the {@link BlobRange} parameter.

+ * + *

Code Samples

+ * + * {@codesnippet com.azure.storage.blob.specialized.BlobAsyncClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set} + * + *

For more information, see the + * Azure Docs

+ * + * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. + * @param range {@link BlobRange} + * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel + * transfers parameter is ignored. + * @param options {@link DownloadRetryOptions} + * @param requestConditions {@link BlobRequestConditions} + * @param rangeGetContentMd5 Whether the contentMD5 for the specified blob range should be returned. + * @param openOptions {@link OpenOption OpenOptions} to use to configure how to open or create the file. + * @return A reactive response containing the blob properties and metadata. + * @throws IllegalArgumentException If {@code blockSize} is less than 0 or greater than 100MB. + * @throws UncheckedIOException If an I/O error occurs. + */ + public Mono> downloadToFileWithResponse(String filePath, BlobRange range, + ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions options, + BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Set openOptions) { try { return withContext(context -> downloadToFileWithResponse(filePath, range, parallelTransferOptions, options, - requestConditions, rangeGetContentMd5, context)); + requestConditions, rangeGetContentMd5, openOptions, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } @@ -763,24 +839,32 @@ public Mono> downloadToFileWithResponse(String filePath Mono> downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions downloadRetryOptions, - BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Context context) { + BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Set openOptions, + Context context) { BlobRange finalRange = range == null ? new BlobRange(0) : range; final ParallelTransferOptions finalParallelTransferOptions = ModelHelper.populateAndApplyDefaults(parallelTransferOptions); BlobRequestConditions finalConditions = requestConditions == null ? new BlobRequestConditions() : requestConditions; - AsynchronousFileChannel channel = downloadToFileResourceSupplier(filePath); + // Default behavior is not to overwrite + if (openOptions == null) { + openOptions = new HashSet<>(); + openOptions.add(StandardOpenOption.CREATE_NEW); + openOptions.add(StandardOpenOption.WRITE); + openOptions.add(StandardOpenOption.READ); + } + + AsynchronousFileChannel channel = downloadToFileResourceSupplier(filePath, openOptions); return Mono.just(channel) .flatMap(c -> this.downloadToFileImpl(c, finalRange, finalParallelTransferOptions, downloadRetryOptions, finalConditions, rangeGetContentMd5, context)) .doFinally(signalType -> this.downloadToFileCleanup(channel, filePath, signalType)); } - private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath) { + private AsynchronousFileChannel downloadToFileResourceSupplier(String filePath, Set openOptions) { try { - return AsynchronousFileChannel.open(Paths.get(filePath), StandardOpenOption.READ, StandardOpenOption.WRITE, - StandardOpenOption.CREATE_NEW); + return AsynchronousFileChannel.open(Paths.get(filePath), openOptions, null); } catch (IOException e) { throw logger.logExceptionAsError(new UncheckedIOException(e)); } diff --git a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobClientBase.java b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobClientBase.java index ecae0d2751bd0..84e153324265b 100644 --- a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobClientBase.java +++ b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobClientBase.java @@ -41,9 +41,13 @@ import java.io.UncheckedIOException; import java.net.URL; import java.nio.file.FileAlreadyExistsException; +import java.nio.file.OpenOption; +import java.nio.file.StandardOpenOption; import java.time.Duration; import java.time.OffsetDateTime; +import java.util.HashSet; import java.util.Map; +import java.util.Set; import static com.azure.storage.common.implementation.StorageImplUtils.blockWithOptionalTimeout; @@ -454,7 +458,42 @@ public BlobDownloadResponse downloadWithResponse(OutputStream stream, BlobRange * @throws UncheckedIOException If an I/O error occurs */ public BlobProperties downloadToFile(String filePath) { - return downloadToFileWithResponse(filePath, null, null, null, null, false, null, Context.NONE).getValue(); + return downloadToFile(filePath, false); + } + + /** + * Downloads the entire blob into a file specified by the path. + * + *

If overwrite is set to false, the file will be created and must not exist, if the file already exists a + * {@link FileAlreadyExistsException} will be thrown.

+ * + *

Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link + * AppendBlobClient}.

+ * + *

Code Samples

+ * + * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadToFile#String-boolean} + * + *

For more information, see the + * Azure Docs

+ * + * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. + * @param overwrite Whether or not to overwrite the file, should the file exist. + * @return The blob properties and metadata. + * @throws UncheckedIOException If an I/O error occurs + */ + public BlobProperties downloadToFile(String filePath, boolean overwrite) { + Set openOptions = null; + if (overwrite) { + openOptions = new HashSet<>(); + openOptions.add(StandardOpenOption.CREATE); + openOptions.add(StandardOpenOption.TRUNCATE_EXISTING); // If the file already exists and it is opened + // for WRITE access, then its length is truncated to 0. + openOptions.add(StandardOpenOption.READ); + openOptions.add(StandardOpenOption.WRITE); + } + return downloadToFileWithResponse(filePath, null, null, null, null, false, openOptions, null, Context.NONE) + .getValue(); } /** @@ -491,8 +530,49 @@ public BlobProperties downloadToFile(String filePath) { public Response downloadToFileWithResponse(String filePath, BlobRange range, ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions downloadRetryOptions, BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Duration timeout, Context context) { + return downloadToFileWithResponse(filePath, range, parallelTransferOptions, downloadRetryOptions, + requestConditions, rangeGetContentMd5, null, timeout, context); + } + + /** + * Downloads the entire blob into a file specified by the path. + * + *

By default the file will be created and must not exist, if the file already exists a + * {@link FileAlreadyExistsException} will be thrown. To override this behavior, provide appropriate + * {@link OpenOption OpenOptions}

+ * + *

Uploading data must be done from the {@link BlockBlobClient}, {@link PageBlobClient}, or {@link + * AppendBlobClient}.

+ * + *

This method makes an extra HTTP call to get the length of the blob in the beginning. To avoid this extra + * call, provide the {@link BlobRange} parameter.

+ * + *

Code Samples

+ * + * {@codesnippet com.azure.storage.blob.specialized.BlobClientBase.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean-Set-Duration-Context} + * + *

For more information, see the + * Azure Docs

+ * + * @param filePath A non-null {@link OutputStream} instance where the downloaded data will be written. + * @param range {@link BlobRange} + * @param parallelTransferOptions {@link ParallelTransferOptions} to use to download to file. Number of parallel + * transfers parameter is ignored. + * @param downloadRetryOptions {@link DownloadRetryOptions} + * @param requestConditions {@link BlobRequestConditions} + * @param rangeGetContentMd5 Whether the contentMD5 for the specified blob range should be returned. + * @param openOptions {@link OpenOption OpenOptions} to use to configure how to open or create the file. + * @param timeout An optional timeout value beyond which a {@link RuntimeException} will be raised. + * @param context Additional context that is passed through the Http pipeline during the service call. + * @return A response containing the blob properties and metadata. + * @throws UncheckedIOException If an I/O error occurs. + */ + public Response downloadToFileWithResponse(String filePath, BlobRange range, + ParallelTransferOptions parallelTransferOptions, DownloadRetryOptions downloadRetryOptions, + BlobRequestConditions requestConditions, boolean rangeGetContentMd5, Set openOptions, + Duration timeout, Context context) { Mono> download = client.downloadToFileWithResponse(filePath, range, - parallelTransferOptions, downloadRetryOptions, requestConditions, rangeGetContentMd5, context); + parallelTransferOptions, downloadRetryOptions, requestConditions, rangeGetContentMd5, openOptions, context); return blockWithOptionalTimeout(download, timeout); } diff --git a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobOutputStream.java b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobOutputStream.java index c5caea22918af..2ed7d6ca5d183 100644 --- a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobOutputStream.java +++ b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlobOutputStream.java @@ -3,24 +3,28 @@ package com.azure.storage.blob.specialized; import com.azure.core.util.logging.ClientLogger; +import com.azure.storage.blob.BlobAsyncClient; +import com.azure.storage.blob.BlobClientBuilder; +import com.azure.storage.blob.models.AccessTier; import com.azure.storage.blob.models.AppendBlobRequestConditions; +import com.azure.storage.blob.models.BlobHttpHeaders; import com.azure.storage.blob.models.BlobRequestConditions; import com.azure.storage.blob.models.BlobStorageException; +import com.azure.storage.blob.models.CpkInfo; +import com.azure.storage.blob.models.CustomerProvidedKey; import com.azure.storage.blob.models.PageBlobRequestConditions; import com.azure.storage.blob.models.PageRange; +import com.azure.storage.blob.models.ParallelTransferOptions; import com.azure.storage.common.StorageOutputStream; import com.azure.storage.common.implementation.Constants; import reactor.core.publisher.Flux; +import reactor.core.publisher.FluxSink; import reactor.core.publisher.Mono; import reactor.core.scheduler.Schedulers; import java.io.IOException; import java.nio.ByteBuffer; -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.Base64; -import java.util.List; -import java.util.UUID; +import java.util.Map; /** * BlobOutputStream allows for the uploading of data to a blob using a stream-like approach. @@ -37,8 +41,9 @@ static BlobOutputStream appendBlobOutputStream(final AppendBlobAsyncClient clien } static BlobOutputStream blockBlobOutputStream(final BlockBlobAsyncClient client, - final BlobRequestConditions requestConditions) { - return new BlockBlobOutputStream(client, requestConditions); + final ParallelTransferOptions parallelTransferOptions, final BlobHttpHeaders headers, + final Map metadata, final AccessTier tier, final BlobRequestConditions requestConditions) { + return new BlockBlobOutputStream(client, parallelTransferOptions, headers, metadata, tier, requestConditions); } static BlobOutputStream pageBlobOutputStream(final PageBlobAsyncClient client, final PageRange pageRange, @@ -70,6 +75,11 @@ public synchronized void close() throws IOException { } catch (final BlobStorageException e) { throw new IOException(e); } + /* Need this check because for block blob the buffered upload error only manifests itself after commit is + called */ + if (this.lastError != null) { + throw lastError; + } } finally { // if close() is called again, an exception will be thrown this.lastError = new IOException(Constants.STREAM_CLOSED); @@ -134,62 +144,74 @@ void commit() { } private static final class BlockBlobOutputStream extends BlobOutputStream { - private final BlobRequestConditions requestConditions; - private final String blockIdPrefix; - private final List blockList; - private final BlockBlobAsyncClient client; + + private FluxSink sink; + + boolean complete; private BlockBlobOutputStream(final BlockBlobAsyncClient client, - final BlobRequestConditions requestConditions) { + final ParallelTransferOptions parallelTransferOptions, final BlobHttpHeaders headers, + final Map metadata, final AccessTier tier, final BlobRequestConditions requestConditions) { super(BlockBlobClient.MAX_STAGE_BLOCK_BYTES); - this.client = client; - this.requestConditions = (requestConditions == null) ? new BlobRequestConditions() : requestConditions; - this.blockIdPrefix = UUID.randomUUID().toString() + '-'; - this.blockList = new ArrayList<>(); - } - /** - * Generates a new block ID to be used for PutBlock. - * - * @return Base64 encoded block ID - */ - private String getCurrentBlockId() { - String blockIdSuffix = String.format("%06d", this.blockList.size()); - return Base64.getEncoder().encodeToString((this.blockIdPrefix + blockIdSuffix) - .getBytes(StandardCharsets.UTF_8)); - } + BlobAsyncClient blobClient = prepareBuilder(client).buildAsyncClient(); - private Mono writeBlock(Flux blockData, String blockId, long writeLength) { - return client.stageBlockWithResponse(blockId, blockData, writeLength, null, - this.requestConditions.getLeaseId()) - .then() + Flux fbb = Flux.create((FluxSink sink) -> this.sink = sink); + + /* Subscribe by upload takes too long. We need to subscribe so that the sink is actually created. Since + this subscriber doesn't do anything and no data has started flowing, there are no drawbacks to this extra + subscribe. */ + fbb.subscribe(); + + blobClient.uploadWithResponse(fbb, parallelTransferOptions, headers, metadata, tier, requestConditions) + // This allows the operation to continue while maintaining the error that occurred. .onErrorResume(BlobStorageException.class, e -> { this.lastError = new IOException(e); return Mono.empty(); - }); + }) + .doOnTerminate(() -> complete = true) + .subscribe(); } - @Override - protected Mono dispatchWrite(byte[] data, int writeLength, long offset) { - if (writeLength == 0) { - return Mono.empty(); + private BlobClientBuilder prepareBuilder(BlobAsyncClientBase client) { + BlobClientBuilder builder = new BlobClientBuilder() + .pipeline(client.getHttpPipeline()) + .endpoint(client.getBlobUrl()) + .snapshot(client.getSnapshotId()) + .serviceVersion(client.getServiceVersion()); + + CpkInfo cpk = client.getCustomerProvidedKey(); + if (cpk != null) { + builder.customerProvidedKey(new CustomerProvidedKey(cpk.getEncryptionKey())); } - final String blockID = this.getCurrentBlockId(); - this.blockList.add(blockID); + return builder; + } - Flux fbb = Flux.range(0, 1) - .concatMap(pos -> Mono.fromCallable(() -> ByteBuffer.wrap(data, (int) offset, writeLength))); + @Override + void commit() { + sink.complete(); + + // Need to wait until the uploadTask completes + while (!complete) { + try { + Thread.sleep(100L); + } catch (InterruptedException e) { + // Does this need to be caught by logger? + e.printStackTrace(); + } + } + } - return this.writeBlock(fbb.subscribeOn(Schedulers.elastic()), blockID, writeLength); + @Override + protected void writeInternal(final byte[] data, int offset, int length) { + sink.next(ByteBuffer.wrap(data, offset, length)); } - /** - * Commits the blob, for block blob this uploads the block list. - */ + // Never called @Override - synchronized void commit() { - client.commitBlockListWithResponse(this.blockList, null, null, null, this.requestConditions).block(); + protected Mono dispatchWrite(byte[] data, int writeLength, long offset) { + return Mono.empty(); } } diff --git a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlockBlobClient.java b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlockBlobClient.java index 7d8a48e6b8657..08be8ec2e7662 100644 --- a/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlockBlobClient.java +++ b/sdk/storage/azure-storage-blob/src/main/java/com/azure/storage/blob/specialized/BlockBlobClient.java @@ -18,6 +18,7 @@ import com.azure.storage.blob.models.BlockBlobItem; import com.azure.storage.blob.models.BlockList; import com.azure.storage.blob.models.BlockListType; +import com.azure.storage.blob.models.ParallelTransferOptions; import com.azure.storage.common.Utility; import com.azure.storage.common.implementation.Constants; import reactor.core.publisher.Flux; @@ -115,7 +116,29 @@ public BlobOutputStream getBlobOutputStream(boolean overwrite) { * @throws BlobStorageException If a storage service error occurred. */ public BlobOutputStream getBlobOutputStream(BlobRequestConditions requestConditions) { - return BlobOutputStream.blockBlobOutputStream(client, requestConditions); + return getBlobOutputStream(null, null, null, null, requestConditions); + } + + /** + * Creates and opens an output stream to write data to the block blob. If the blob already exists on the service, it + * will be overwritten. + *

+ * To avoid overwriting, pass "*" to {@link BlobRequestConditions#setIfNoneMatch(String)}. + * + * @param parallelTransferOptions {@link ParallelTransferOptions} used to configure buffered uploading. + * @param headers {@link BlobHttpHeaders} + * @param metadata Metadata to associate with the blob. + * @param tier {@link AccessTier} for the destination blob. + * @param requestConditions {@link BlobRequestConditions} + * + * @return A {@link BlobOutputStream} object used to write data to the blob. + * @throws BlobStorageException If a storage service error occurred. + */ + public BlobOutputStream getBlobOutputStream(ParallelTransferOptions parallelTransferOptions, + BlobHttpHeaders headers, Map metadata, AccessTier tier, + BlobRequestConditions requestConditions) { + return BlobOutputStream.blockBlobOutputStream(client, parallelTransferOptions, headers, metadata, tier, + requestConditions); } /** diff --git a/sdk/storage/azure-storage-blob/src/samples/java/com/azure/storage/blob/specialized/BlobAsyncClientBaseJavaDocCodeSnippets.java b/sdk/storage/azure-storage-blob/src/samples/java/com/azure/storage/blob/specialized/BlobAsyncClientBaseJavaDocCodeSnippets.java index 0e27f16247393..80bac6da0e856 100644 --- a/sdk/storage/azure-storage-blob/src/samples/java/com/azure/storage/blob/specialized/BlobAsyncClientBaseJavaDocCodeSnippets.java +++ b/sdk/storage/azure-storage-blob/src/samples/java/com/azure/storage/blob/specialized/BlobAsyncClientBaseJavaDocCodeSnippets.java @@ -24,10 +24,15 @@ 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; /** * Code snippets for {@link BlobAsyncClientBase} @@ -130,14 +135,28 @@ public void downloadToFileCodeSnippet() { 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.downloadToFileWithResponse#String-BlobRange-ParallelTransferOptions-DownloadRetryOptions-BlobRequestConditions-boolean + // 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 } /** diff --git a/sdk/storage/azure-storage-blob/src/samples/java/com/azure/storage/blob/specialized/BlobClientBaseJavaDocCodeSnippets.java b/sdk/storage/azure-storage-blob/src/samples/java/com/azure/storage/blob/specialized/BlobClientBaseJavaDocCodeSnippets.java index 2cd4e3c850d84..c1000abd32d47 100644 --- a/sdk/storage/azure-storage-blob/src/samples/java/com/azure/storage/blob/specialized/BlobClientBaseJavaDocCodeSnippets.java +++ b/sdk/storage/azure-storage-blob/src/samples/java/com/azure/storage/blob/specialized/BlobClientBaseJavaDocCodeSnippets.java @@ -28,10 +28,15 @@ import java.io.ByteArrayOutputStream; 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; /** * Code snippets for {@link BlobClientBase} @@ -110,6 +115,12 @@ public void downloadToFile() { 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); @@ -118,6 +129,17 @@ public void downloadToFile() { 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(4 * Constants.MB, null, null), + 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 } /** diff --git a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/APISpec.groovy b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/APISpec.groovy index 6de4d356360eb..0744998a5598a 100644 --- a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/APISpec.groovy +++ b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/APISpec.groovy @@ -164,6 +164,9 @@ class APISpec extends Specification { this.interceptorManager = new InterceptorManager(className + fullTestName, testMode) this.resourceNamer = new TestResourceNamer(className + testName, testMode, interceptorManager.getRecordedData()) + // Print out the test name to create breadcrumbs in our test logging in case anything hangs. + System.out.printf("========================= %s.%s =========================%n", className, fullTestName) + // If the test doesn't have the Requires tag record it in live mode. recordLiveMode = specificationContext.getCurrentIteration().getDescription().getAnnotation(Requires.class) != null diff --git a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/BlobAPITest.groovy b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/BlobAPITest.groovy index 5628bb0fef5fd..7a59ec06d6cf3 100644 --- a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/BlobAPITest.groovy +++ b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/BlobAPITest.groovy @@ -36,9 +36,12 @@ import spock.lang.Requires import spock.lang.Unroll import java.nio.ByteBuffer +import java.nio.channels.NonWritableChannelException import java.nio.charset.StandardCharsets import java.nio.file.FileAlreadyExistsException import java.nio.file.Files +import java.nio.file.OpenOption +import java.nio.file.StandardOpenOption import java.security.MessageDigest import java.time.Duration import java.time.OffsetDateTime @@ -263,6 +266,7 @@ class BlobAPITest extends APISpec { } when: + // Default overwrite is false so this should fail bc.downloadToFile(testFile.getPath()) then: @@ -273,6 +277,23 @@ class BlobAPITest extends APISpec { testFile.delete() } + def "Download to file exists succeeds"() { + setup: + def testFile = new File(testName + ".txt") + if (!testFile.exists()) { + assert testFile.createNewFile() + } + + when: + bc.downloadToFile(testFile.getPath(), true) + + then: + new String(Files.readAllBytes(testFile.toPath()), StandardCharsets.UTF_8) == defaultText + + cleanup: + testFile.delete() + } + def "Download to file does not exist"() { setup: def testFile = new File(testName + ".txt") @@ -290,6 +311,49 @@ class BlobAPITest extends APISpec { testFile.delete() } + def "Download file does not exist open options"() { + setup: + def testFile = new File(testName + ".txt") + if (testFile.exists()) { + assert testFile.delete() + } + + when: + Set openOptions = new HashSet<>() + openOptions.add(StandardOpenOption.CREATE_NEW) + openOptions.add(StandardOpenOption.READ) + openOptions.add(StandardOpenOption.WRITE) + bc.downloadToFileWithResponse(testFile.getPath(), null, null, null, null, false, openOptions, null, null) + + then: + new String(Files.readAllBytes(testFile.toPath()), StandardCharsets.UTF_8) == defaultText + + cleanup: + testFile.delete() + } + + def "Download file exist open options"() { + setup: + def testFile = new File(testName + ".txt") + if (!testFile.exists()) { + assert testFile.createNewFile() + } + + when: + Set openOptions = new HashSet<>() + openOptions.add(StandardOpenOption.CREATE) + openOptions.add(StandardOpenOption.TRUNCATE_EXISTING) + openOptions.add(StandardOpenOption.READ) + openOptions.add(StandardOpenOption.WRITE) + bc.downloadToFileWithResponse(testFile.getPath(), null, null, null, null, false, openOptions, null, null) + + then: + new String(Files.readAllBytes(testFile.toPath()), StandardCharsets.UTF_8) == defaultText + + cleanup: + testFile.delete() + } + @Requires({ liveMode() }) @Unroll def "Download file"() { diff --git a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/BlobOutputStreamTest.groovy b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/BlobOutputStreamTest.groovy index d42f857fee31b..667013540f7da 100644 --- a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/BlobOutputStreamTest.groovy +++ b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/BlobOutputStreamTest.groovy @@ -39,7 +39,6 @@ class BlobOutputStreamTest extends APISpec { and: blockBlobClient.getBlobOutputStream() - then: thrown(IllegalArgumentException) } diff --git a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/SASTest.groovy b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/SASTest.groovy index 4b9c4f4a8a4aa..96359087d018b 100644 --- a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/SASTest.groovy +++ b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/SASTest.groovy @@ -1199,6 +1199,7 @@ class SASTest extends APISpec { } // TODO : Figure out how to properly port this test over since I changed it to a common sas params + @Ignore def "BlobURLParts"() { setup: def parts = new BlobUrlParts() diff --git a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/SasClientTests.groovy b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/SasClientTests.groovy index 54a1517258d2f..24ed0b81538ff 100644 --- a/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/SasClientTests.groovy +++ b/sdk/storage/azure-storage-blob/src/test/java/com/azure/storage/blob/SasClientTests.groovy @@ -19,7 +19,6 @@ import com.azure.storage.common.sas.AccountSasService import com.azure.storage.common.sas.AccountSasSignatureValues import com.azure.storage.common.sas.SasIpRange import com.azure.storage.common.sas.SasProtocol -import spock.lang.Ignore import spock.lang.Unroll import java.time.LocalDateTime diff --git a/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadfiledoesnotexistopenoptions.json b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadfiledoesnotexistopenoptions.json new file mode 100644 index 0000000000000..b9a809806b7ec --- /dev/null +++ b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadfiledoesnotexistopenoptions.json @@ -0,0 +1,121 @@ +{ + "networkCallRecords" : [ { + "Method" : "PUT", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadfiledoesnotexistopenoptions02899367a6b4e79?restype=container", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "250e22c7-c995-4ddf-a3ba-efc27723e0f2" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "ETag" : "0x8D785A6954049C0", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:41 GMT", + "retry-after" : "0", + "Content-Length" : "0", + "StatusCode" : "201", + "x-ms-request-id" : "c72e9cc0-001e-0016-5c8f-b764ec000000", + "Date" : "Fri, 20 Dec 2019 23:44:40 GMT", + "x-ms-client-request-id" : "250e22c7-c995-4ddf-a3ba-efc27723e0f2" + }, + "Exception" : null + }, { + "Method" : "PUT", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadfiledoesnotexistopenoptions02899367a6b4e79/javablobdownloadfiledoesnotexistopenoptions11894382a29b9", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "4e421bd1-c9a7-4359-a195-9c1d556fe5f5", + "Content-Type" : "application/octet-stream" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "x-ms-content-crc64" : "6RYQPwaVsyQ=", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:41 GMT", + "retry-after" : "0", + "StatusCode" : "201", + "x-ms-request-server-encrypted" : "true", + "Date" : "Fri, 20 Dec 2019 23:44:40 GMT", + "Content-MD5" : "wh+Wm18D0z1D4E+PE252gg==", + "ETag" : "0x8D785A6955FA3AD", + "Content-Length" : "0", + "x-ms-request-id" : "c72e9cd5-001e-0016-6f8f-b764ec000000", + "x-ms-client-request-id" : "4e421bd1-c9a7-4359-a195-9c1d556fe5f5" + }, + "Exception" : null + }, { + "Method" : "GET", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadfiledoesnotexistopenoptions02899367a6b4e79/javablobdownloadfiledoesnotexistopenoptions11894382a29b9", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "d8a96f02-a74d-4be4-842e-0541803e9471" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "x-ms-lease-status" : "unlocked", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "Content-Range" : "bytes 0-6/7", + "x-ms-lease-state" : "available", + "x-ms-blob-content-md5" : "wh+Wm18D0z1D4E+PE252gg==", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:41 GMT", + "retry-after" : "0", + "StatusCode" : "206", + "Date" : "Fri, 20 Dec 2019 23:44:40 GMT", + "x-ms-blob-type" : "BlockBlob", + "Accept-Ranges" : "bytes", + "x-ms-server-encrypted" : "true", + "ETag" : "0x8D785A6955FA3AD", + "x-ms-creation-time" : "Fri, 20 Dec 2019 23:44:41 GMT", + "Content-Length" : "7", + "x-ms-request-id" : "c72e9cde-001e-0016-788f-b764ec000000", + "Body" : "[100, 101, 102, 97, 117, 108, 116]", + "x-ms-client-request-id" : "d8a96f02-a74d-4be4-842e-0541803e9471", + "Content-Type" : "application/octet-stream" + }, + "Exception" : null + }, { + "Method" : "GET", + "Uri" : "https://gaprastg71.blob.core.windows.net?prefix=jtcdownloadfiledoesnotexistopenoptions&comp=list", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "52ddb186-fb70-4870-9c86-2df33ed1990b" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "retry-after" : "0", + "StatusCode" : "200", + "x-ms-request-id" : "c72e9cf4-001e-0016-0e8f-b764ec000000", + "Body" : "jtcdownloadfiledoesnotexistopenoptionsjtcdownloadfiledoesnotexistopenoptions02899367a6b4e79Fri, 20 Dec 2019 23:44:41 GMT\"0x8D785A6954049C0\"unlockedavailable$account-encryption-keyfalsefalsefalse", + "Date" : "Fri, 20 Dec 2019 23:44:40 GMT", + "x-ms-client-request-id" : "52ddb186-fb70-4870-9c86-2df33ed1990b", + "Content-Type" : "application/xml" + }, + "Exception" : null + }, { + "Method" : "DELETE", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadfiledoesnotexistopenoptions02899367a6b4e79?restype=container", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "9adcbc59-e868-492e-b48b-91122018b2db" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "retry-after" : "0", + "Content-Length" : "0", + "StatusCode" : "202", + "x-ms-request-id" : "c72e9d09-001e-0016-228f-b764ec000000", + "Date" : "Fri, 20 Dec 2019 23:44:40 GMT", + "x-ms-client-request-id" : "9adcbc59-e868-492e-b48b-91122018b2db" + }, + "Exception" : null + } ], + "variables" : [ "jtcdownloadfiledoesnotexistopenoptions02899367a6b4e79", "javablobdownloadfiledoesnotexistopenoptions11894382a29b9" ] +} \ No newline at end of file diff --git a/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadfileexistopenoptions.json b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadfileexistopenoptions.json new file mode 100644 index 0000000000000..85d7435f6a092 --- /dev/null +++ b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadfileexistopenoptions.json @@ -0,0 +1,121 @@ +{ + "networkCallRecords" : [ { + "Method" : "PUT", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadfileexistopenoptions04880095a4282c15bc4?restype=container", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "7bbc621e-d546-4595-8e6e-d2f2d251bd3d" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "ETag" : "0x8D785A698DA9CBA", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:47 GMT", + "retry-after" : "0", + "Content-Length" : "0", + "StatusCode" : "201", + "x-ms-request-id" : "d4138152-b01e-003c-1f8f-b7bbfc000000", + "Date" : "Fri, 20 Dec 2019 23:44:46 GMT", + "x-ms-client-request-id" : "7bbc621e-d546-4595-8e6e-d2f2d251bd3d" + }, + "Exception" : null + }, { + "Method" : "PUT", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadfileexistopenoptions04880095a4282c15bc4/javablobdownloadfileexistopenoptions165910938502956c", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "c81853c1-60ed-4d0f-92dc-82da3705a1ef", + "Content-Type" : "application/octet-stream" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "x-ms-content-crc64" : "6RYQPwaVsyQ=", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:47 GMT", + "retry-after" : "0", + "StatusCode" : "201", + "x-ms-request-server-encrypted" : "true", + "Date" : "Fri, 20 Dec 2019 23:44:46 GMT", + "Content-MD5" : "wh+Wm18D0z1D4E+PE252gg==", + "ETag" : "0x8D785A698FAF169", + "Content-Length" : "0", + "x-ms-request-id" : "d413816e-b01e-003c-388f-b7bbfc000000", + "x-ms-client-request-id" : "c81853c1-60ed-4d0f-92dc-82da3705a1ef" + }, + "Exception" : null + }, { + "Method" : "GET", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadfileexistopenoptions04880095a4282c15bc4/javablobdownloadfileexistopenoptions165910938502956c", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "d44d712c-f3c7-4080-8757-e4c4519261df" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "x-ms-lease-status" : "unlocked", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "Content-Range" : "bytes 0-6/7", + "x-ms-lease-state" : "available", + "x-ms-blob-content-md5" : "wh+Wm18D0z1D4E+PE252gg==", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:47 GMT", + "retry-after" : "0", + "StatusCode" : "206", + "Date" : "Fri, 20 Dec 2019 23:44:46 GMT", + "x-ms-blob-type" : "BlockBlob", + "Accept-Ranges" : "bytes", + "x-ms-server-encrypted" : "true", + "ETag" : "0x8D785A698FAF169", + "x-ms-creation-time" : "Fri, 20 Dec 2019 23:44:47 GMT", + "Content-Length" : "7", + "x-ms-request-id" : "d413817a-b01e-003c-448f-b7bbfc000000", + "Body" : "[100, 101, 102, 97, 117, 108, 116]", + "x-ms-client-request-id" : "d44d712c-f3c7-4080-8757-e4c4519261df", + "Content-Type" : "application/octet-stream" + }, + "Exception" : null + }, { + "Method" : "GET", + "Uri" : "https://gaprastg71.blob.core.windows.net?prefix=jtcdownloadfileexistopenoptions&comp=list", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "2174cd50-6809-460c-918e-baa431f8d1f1" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "retry-after" : "0", + "StatusCode" : "200", + "x-ms-request-id" : "d4138188-b01e-003c-518f-b7bbfc000000", + "Body" : "jtcdownloadfileexistopenoptionsjtcdownloadfileexistopenoptions04880095a4282c15bc4Fri, 20 Dec 2019 23:44:47 GMT\"0x8D785A698DA9CBA\"unlockedavailable$account-encryption-keyfalsefalsefalse", + "Date" : "Fri, 20 Dec 2019 23:44:47 GMT", + "x-ms-client-request-id" : "2174cd50-6809-460c-918e-baa431f8d1f1", + "Content-Type" : "application/xml" + }, + "Exception" : null + }, { + "Method" : "DELETE", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadfileexistopenoptions04880095a4282c15bc4?restype=container", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "c7b8cec4-d64b-41bd-9886-39d9e41f9c95" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "retry-after" : "0", + "Content-Length" : "0", + "StatusCode" : "202", + "x-ms-request-id" : "d4138193-b01e-003c-5c8f-b7bbfc000000", + "Date" : "Fri, 20 Dec 2019 23:44:47 GMT", + "x-ms-client-request-id" : "c7b8cec4-d64b-41bd-9886-39d9e41f9c95" + }, + "Exception" : null + } ], + "variables" : [ "jtcdownloadfileexistopenoptions04880095a4282c15bc4", "javablobdownloadfileexistopenoptions165910938502956c" ] +} \ No newline at end of file diff --git a/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofiledoesnotexist.json b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofiledoesnotexist.json index d77e531edd6ea..106bd912697f1 100644 --- a/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofiledoesnotexist.json +++ b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofiledoesnotexist.json @@ -1,88 +1,57 @@ { "networkCallRecords" : [ { "Method" : "PUT", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net/jtcdownloadtofiledoesnotexist0128346b089568604141?restype=container", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofiledoesnotexist0024275cbd3672129344?restype=container", "Headers" : { "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "d5278936-f352-4300-9879-c3f6e7831de7" + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "2c602f4e-2286-4c53-a71b-5c1bb4e85418" }, "Response" : { "x-ms-version" : "2019-02-02", "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", - "ETag" : "0x8D75A7E30E8ADFB", - "Last-Modified" : "Sun, 27 Oct 2019 01:37:12 GMT", + "ETag" : "0x8D785A68D2E8A64", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:27 GMT", "retry-after" : "0", "Content-Length" : "0", "StatusCode" : "201", - "x-ms-request-id" : "161e6599-301e-013a-3a67-8c3580000000", - "Date" : "Sun, 27 Oct 2019 01:37:12 GMT", - "x-ms-client-request-id" : "d5278936-f352-4300-9879-c3f6e7831de7" + "x-ms-request-id" : "135ab365-501e-001b-3e8f-b7ac38000000", + "Date" : "Fri, 20 Dec 2019 23:44:26 GMT", + "x-ms-client-request-id" : "2c602f4e-2286-4c53-a71b-5c1bb4e85418" }, "Exception" : null }, { "Method" : "PUT", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net/jtcdownloadtofiledoesnotexist0128346b089568604141/javablobdownloadtofiledoesnotexist191575f30f3eaddd5", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofiledoesnotexist0024275cbd3672129344/javablobdownloadtofiledoesnotexist1944333aaba2cac77", "Headers" : { "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "e82ecd76-97a6-4dd5-a4c8-3fb987d693ca", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "f211c0b3-732f-49ee-bb03-2bec04acf497", "Content-Type" : "application/octet-stream" }, "Response" : { "x-ms-version" : "2019-02-02", "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", "x-ms-content-crc64" : "6RYQPwaVsyQ=", - "Last-Modified" : "Sun, 27 Oct 2019 01:37:12 GMT", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:27 GMT", "retry-after" : "0", "StatusCode" : "201", "x-ms-request-server-encrypted" : "true", - "Date" : "Sun, 27 Oct 2019 01:37:12 GMT", + "Date" : "Fri, 20 Dec 2019 23:44:26 GMT", "Content-MD5" : "wh+Wm18D0z1D4E+PE252gg==", - "ETag" : "0x8D75A7E30F07167", + "ETag" : "0x8D785A68D4EF9AC", "Content-Length" : "0", - "x-ms-request-id" : "161e65a1-301e-013a-4167-8c3580000000", - "x-ms-client-request-id" : "e82ecd76-97a6-4dd5-a4c8-3fb987d693ca" - }, - "Exception" : null - }, { - "Method" : "HEAD", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net/jtcdownloadtofiledoesnotexist0128346b089568604141/javablobdownloadtofiledoesnotexist191575f30f3eaddd5", - "Headers" : { - "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "c27b5db0-fc65-4c2a-9c6e-556c5dc21573" - }, - "Response" : { - "x-ms-version" : "2019-02-02", - "x-ms-lease-status" : "unlocked", - "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", - "x-ms-lease-state" : "available", - "Last-Modified" : "Sun, 27 Oct 2019 01:37:12 GMT", - "retry-after" : "0", - "StatusCode" : "200", - "Date" : "Sun, 27 Oct 2019 01:37:12 GMT", - "x-ms-blob-type" : "BlockBlob", - "Content-MD5" : "wh+Wm18D0z1D4E+PE252gg==", - "Accept-Ranges" : "bytes", - "x-ms-server-encrypted" : "true", - "x-ms-access-tier-inferred" : "true", - "x-ms-access-tier" : "Hot", - "ETag" : "0x8D75A7E30F07167", - "x-ms-creation-time" : "Sun, 27 Oct 2019 01:37:12 GMT", - "Content-Length" : "7", - "x-ms-request-id" : "161e65b4-301e-013a-4c67-8c3580000000", - "x-ms-client-request-id" : "c27b5db0-fc65-4c2a-9c6e-556c5dc21573", - "Content-Type" : "application/octet-stream" + "x-ms-request-id" : "135ab371-501e-001b-478f-b7ac38000000", + "x-ms-client-request-id" : "f211c0b3-732f-49ee-bb03-2bec04acf497" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net/jtcdownloadtofiledoesnotexist0128346b089568604141/javablobdownloadtofiledoesnotexist191575f30f3eaddd5", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofiledoesnotexist0024275cbd3672129344/javablobdownloadtofiledoesnotexist1944333aaba2cac77", "Headers" : { "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "17b03287-090c-498f-9917-6d683fca860b" + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "81e0f400-6d7e-4628-a241-8c2e0fb89e24" }, "Response" : { "x-ms-version" : "2019-02-02", @@ -91,29 +60,29 @@ "Content-Range" : "bytes 0-6/7", "x-ms-lease-state" : "available", "x-ms-blob-content-md5" : "wh+Wm18D0z1D4E+PE252gg==", - "Last-Modified" : "Sun, 27 Oct 2019 01:37:12 GMT", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:27 GMT", "retry-after" : "0", "StatusCode" : "206", - "Date" : "Sun, 27 Oct 2019 01:37:13 GMT", + "Date" : "Fri, 20 Dec 2019 23:44:26 GMT", "x-ms-blob-type" : "BlockBlob", "Accept-Ranges" : "bytes", "x-ms-server-encrypted" : "true", - "ETag" : "0x8D75A7E30F07167", - "x-ms-creation-time" : "Sun, 27 Oct 2019 01:37:12 GMT", + "ETag" : "0x8D785A68D4EF9AC", + "x-ms-creation-time" : "Fri, 20 Dec 2019 23:44:27 GMT", "Content-Length" : "7", - "x-ms-request-id" : "161e65c0-301e-013a-5767-8c3580000000", + "x-ms-request-id" : "135ab378-501e-001b-4e8f-b7ac38000000", "Body" : "[100, 101, 102, 97, 117, 108, 116]", - "x-ms-client-request-id" : "17b03287-090c-498f-9917-6d683fca860b", + "x-ms-client-request-id" : "81e0f400-6d7e-4628-a241-8c2e0fb89e24", "Content-Type" : "application/octet-stream" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net?prefix=jtcdownloadtofiledoesnotexist&comp=list", + "Uri" : "https://gaprastg71.blob.core.windows.net?prefix=jtcdownloadtofiledoesnotexist&comp=list", "Headers" : { "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "6a0bdeb4-e335-44ce-b68f-a1945400381a" + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "866138f8-a63b-4566-8128-b10096fa9674" }, "Response" : { "Transfer-Encoding" : "chunked", @@ -121,20 +90,20 @@ "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", "retry-after" : "0", "StatusCode" : "200", - "x-ms-request-id" : "161e65d8-301e-013a-6967-8c3580000000", - "Body" : "jtcdownloadtofiledoesnotexistjtcdownloadtofiledoesnotexist0128346b089568604141Sun, 27 Oct 2019 01:37:12 GMT\"0x8D75A7E30E8ADFB\"unlockedavailable$account-encryption-keyfalsefalsefalse", - "Date" : "Sun, 27 Oct 2019 01:37:13 GMT", - "x-ms-client-request-id" : "6a0bdeb4-e335-44ce-b68f-a1945400381a", + "x-ms-request-id" : "135ab37b-501e-001b-518f-b7ac38000000", + "Body" : "jtcdownloadtofiledoesnotexistjtcdownloadtofiledoesnotexist0024275cbd3672129344Fri, 20 Dec 2019 23:44:27 GMT\"0x8D785A68D2E8A64\"unlockedavailable$account-encryption-keyfalsefalsefalse", + "Date" : "Fri, 20 Dec 2019 23:44:27 GMT", + "x-ms-client-request-id" : "866138f8-a63b-4566-8128-b10096fa9674", "Content-Type" : "application/xml" }, "Exception" : null }, { "Method" : "DELETE", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net/jtcdownloadtofiledoesnotexist0128346b089568604141?restype=container", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofiledoesnotexist0024275cbd3672129344?restype=container", "Headers" : { "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "665eb1d1-1bb8-4c21-90a6-1948707af336" + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "c3e54cd1-64ec-47dd-b028-872c88a8a515" }, "Response" : { "x-ms-version" : "2019-02-02", @@ -142,11 +111,11 @@ "retry-after" : "0", "Content-Length" : "0", "StatusCode" : "202", - "x-ms-request-id" : "161e65e3-301e-013a-7267-8c3580000000", - "Date" : "Sun, 27 Oct 2019 01:37:13 GMT", - "x-ms-client-request-id" : "665eb1d1-1bb8-4c21-90a6-1948707af336" + "x-ms-request-id" : "135ab382-501e-001b-588f-b7ac38000000", + "Date" : "Fri, 20 Dec 2019 23:44:27 GMT", + "x-ms-client-request-id" : "c3e54cd1-64ec-47dd-b028-872c88a8a515" }, "Exception" : null } ], - "variables" : [ "jtcdownloadtofiledoesnotexist0128346b089568604141", "javablobdownloadtofiledoesnotexist191575f30f3eaddd5" ] + "variables" : [ "jtcdownloadtofiledoesnotexist0024275cbd3672129344", "javablobdownloadtofiledoesnotexist1944333aaba2cac77" ] } \ No newline at end of file diff --git a/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofileexists.json b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofileexists.json index e7c5e5baca0b1..4f658045b66a1 100644 --- a/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofileexists.json +++ b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofileexists.json @@ -1,57 +1,57 @@ { "networkCallRecords" : [ { "Method" : "PUT", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net/jtcdownloadtofileexists0298267b4b3ff5b0d344fb9?restype=container", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofileexists096284cd349d96e6894615b?restype=container", "Headers" : { "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "9e84f432-dfb5-401b-a789-95227683f273" + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "877308ef-878c-4e5f-8297-c340f9b6f12b" }, "Response" : { "x-ms-version" : "2019-02-02", "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", - "ETag" : "0x8D75A7E30C650A7", - "Last-Modified" : "Sun, 27 Oct 2019 01:37:12 GMT", + "ETag" : "0x8D785A6859A6889", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:14 GMT", "retry-after" : "0", "Content-Length" : "0", "StatusCode" : "201", - "x-ms-request-id" : "161e6566-301e-013a-0f67-8c3580000000", - "Date" : "Sun, 27 Oct 2019 01:37:12 GMT", - "x-ms-client-request-id" : "9e84f432-dfb5-401b-a789-95227683f273" + "x-ms-request-id" : "3f3f5c68-501e-0024-5c8f-b7649b000000", + "Date" : "Fri, 20 Dec 2019 23:44:14 GMT", + "x-ms-client-request-id" : "877308ef-878c-4e5f-8297-c340f9b6f12b" }, "Exception" : null }, { "Method" : "PUT", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net/jtcdownloadtofileexists0298267b4b3ff5b0d344fb9/javablobdownloadtofileexists199775a51f46ceaa9c41", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofileexists096284cd349d96e6894615b/javablobdownloadtofileexists160998f87cd14a25c740", "Headers" : { "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "a63a0a6a-a5dc-4a9a-92c3-7d642d473a41", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "c6c2734a-34a2-4681-a3c2-95bceb1d7f12", "Content-Type" : "application/octet-stream" }, "Response" : { "x-ms-version" : "2019-02-02", "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", "x-ms-content-crc64" : "6RYQPwaVsyQ=", - "Last-Modified" : "Sun, 27 Oct 2019 01:37:12 GMT", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:15 GMT", "retry-after" : "0", "StatusCode" : "201", "x-ms-request-server-encrypted" : "true", - "Date" : "Sun, 27 Oct 2019 01:37:12 GMT", + "Date" : "Fri, 20 Dec 2019 23:44:14 GMT", "Content-MD5" : "wh+Wm18D0z1D4E+PE252gg==", - "ETag" : "0x8D75A7E30D05E86", + "ETag" : "0x8D785A685B95044", "Content-Length" : "0", - "x-ms-request-id" : "161e657c-301e-013a-2067-8c3580000000", - "x-ms-client-request-id" : "a63a0a6a-a5dc-4a9a-92c3-7d642d473a41" + "x-ms-request-id" : "3f3f5c7e-501e-0024-708f-b7649b000000", + "x-ms-client-request-id" : "c6c2734a-34a2-4681-a3c2-95bceb1d7f12" }, "Exception" : null }, { "Method" : "GET", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net?prefix=jtcdownloadtofileexists&comp=list", + "Uri" : "https://gaprastg71.blob.core.windows.net?prefix=jtcdownloadtofileexists&comp=list", "Headers" : { "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "ceb77eea-d2a7-4a31-a953-028e10262c3b" + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "4da31a8e-7637-4c10-841e-03a576d0df6f" }, "Response" : { "Transfer-Encoding" : "chunked", @@ -59,20 +59,20 @@ "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", "retry-after" : "0", "StatusCode" : "200", - "x-ms-request-id" : "161e6585-301e-013a-2867-8c3580000000", - "Body" : "jtcdownloadtofileexistsjtcdownloadtofileexists0298267b4b3ff5b0d344fb9Sun, 27 Oct 2019 01:37:12 GMT\"0x8D75A7E30C650A7\"unlockedavailable$account-encryption-keyfalsefalsefalse", - "Date" : "Sun, 27 Oct 2019 01:37:12 GMT", - "x-ms-client-request-id" : "ceb77eea-d2a7-4a31-a953-028e10262c3b", + "x-ms-request-id" : "3f3f5c82-501e-0024-748f-b7649b000000", + "Body" : "jtcdownloadtofileexistsjtcdownloadtofileexists096284cd349d96e6894615bFri, 20 Dec 2019 23:44:14 GMT\"0x8D785A6859A6889\"unlockedavailable$account-encryption-keyfalsefalsefalse", + "Date" : "Fri, 20 Dec 2019 23:44:15 GMT", + "x-ms-client-request-id" : "4da31a8e-7637-4c10-841e-03a576d0df6f", "Content-Type" : "application/xml" }, "Exception" : null }, { "Method" : "DELETE", - "Uri" : "https://azstoragesdkaccount.blob.core.windows.net/jtcdownloadtofileexists0298267b4b3ff5b0d344fb9?restype=container", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofileexists096284cd349d96e6894615b?restype=container", "Headers" : { "x-ms-version" : "2019-02-02", - "User-Agent" : "azsdk-java-azure-storage-blob/12.0.0-preview.5 1.8.0_221; Mac OS X 10.14.6", - "x-ms-client-request-id" : "c7a43be8-e4e2-49bd-b327-a6901be20a9e" + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "1060987e-9486-4e1b-b720-c0745ab8e47c" }, "Response" : { "x-ms-version" : "2019-02-02", @@ -80,11 +80,11 @@ "retry-after" : "0", "Content-Length" : "0", "StatusCode" : "202", - "x-ms-request-id" : "161e6590-301e-013a-3367-8c3580000000", - "Date" : "Sun, 27 Oct 2019 01:37:12 GMT", - "x-ms-client-request-id" : "c7a43be8-e4e2-49bd-b327-a6901be20a9e" + "x-ms-request-id" : "3f3f5c87-501e-0024-788f-b7649b000000", + "Date" : "Fri, 20 Dec 2019 23:44:15 GMT", + "x-ms-client-request-id" : "1060987e-9486-4e1b-b720-c0745ab8e47c" }, "Exception" : null } ], - "variables" : [ "jtcdownloadtofileexists0298267b4b3ff5b0d344fb9", "javablobdownloadtofileexists199775a51f46ceaa9c41" ] + "variables" : [ "jtcdownloadtofileexists096284cd349d96e6894615b", "javablobdownloadtofileexists160998f87cd14a25c740" ] } \ No newline at end of file diff --git a/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofileexistssucceeds.json b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofileexistssucceeds.json new file mode 100644 index 0000000000000..fc1e373ebb7ca --- /dev/null +++ b/sdk/storage/azure-storage-blob/src/test/resources/session-records/BlobAPITestdownloadtofileexistssucceeds.json @@ -0,0 +1,121 @@ +{ + "networkCallRecords" : [ { + "Method" : "PUT", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofileexistssucceeds087572dd477056d04a4?restype=container", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "dfdd82b9-c5a7-4197-8c2b-a47e0d12b206" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "ETag" : "0x8D785A689017FC1", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:20 GMT", + "retry-after" : "0", + "Content-Length" : "0", + "StatusCode" : "201", + "x-ms-request-id" : "bfd6dcfc-001e-0029-728f-b7ac4f000000", + "Date" : "Fri, 20 Dec 2019 23:44:20 GMT", + "x-ms-client-request-id" : "dfdd82b9-c5a7-4197-8c2b-a47e0d12b206" + }, + "Exception" : null + }, { + "Method" : "PUT", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofileexistssucceeds087572dd477056d04a4/javablobdownloadtofileexistssucceeds107956e96a6f95a8", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "12ba715d-8099-46db-b600-bfad65edd707", + "Content-Type" : "application/octet-stream" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "x-ms-content-crc64" : "6RYQPwaVsyQ=", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:20 GMT", + "retry-after" : "0", + "StatusCode" : "201", + "x-ms-request-server-encrypted" : "true", + "Date" : "Fri, 20 Dec 2019 23:44:20 GMT", + "Content-MD5" : "wh+Wm18D0z1D4E+PE252gg==", + "ETag" : "0x8D785A689237A1F", + "Content-Length" : "0", + "x-ms-request-id" : "bfd6dd03-001e-0029-778f-b7ac4f000000", + "x-ms-client-request-id" : "12ba715d-8099-46db-b600-bfad65edd707" + }, + "Exception" : null + }, { + "Method" : "GET", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofileexistssucceeds087572dd477056d04a4/javablobdownloadtofileexistssucceeds107956e96a6f95a8", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "e5410772-924f-4cbe-9e60-0a3038ac0219" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "x-ms-lease-status" : "unlocked", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "Content-Range" : "bytes 0-6/7", + "x-ms-lease-state" : "available", + "x-ms-blob-content-md5" : "wh+Wm18D0z1D4E+PE252gg==", + "Last-Modified" : "Fri, 20 Dec 2019 23:44:20 GMT", + "retry-after" : "0", + "StatusCode" : "206", + "Date" : "Fri, 20 Dec 2019 23:44:20 GMT", + "x-ms-blob-type" : "BlockBlob", + "Accept-Ranges" : "bytes", + "x-ms-server-encrypted" : "true", + "ETag" : "0x8D785A689237A1F", + "x-ms-creation-time" : "Fri, 20 Dec 2019 23:44:20 GMT", + "Content-Length" : "7", + "x-ms-request-id" : "bfd6dd0a-001e-0029-7e8f-b7ac4f000000", + "Body" : "[100, 101, 102, 97, 117, 108, 116]", + "x-ms-client-request-id" : "e5410772-924f-4cbe-9e60-0a3038ac0219", + "Content-Type" : "application/octet-stream" + }, + "Exception" : null + }, { + "Method" : "GET", + "Uri" : "https://gaprastg71.blob.core.windows.net?prefix=jtcdownloadtofileexistssucceeds&comp=list", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "833f516e-de8c-4c85-b5d7-4a2cf61224af" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "retry-after" : "0", + "StatusCode" : "200", + "x-ms-request-id" : "bfd6dd13-001e-0029-078f-b7ac4f000000", + "Body" : "jtcdownloadtofileexistssucceedsjtcdownloadtofileexistssucceeds087572dd477056d04a4Fri, 20 Dec 2019 23:44:20 GMT\"0x8D785A689017FC1\"unlockedavailable$account-encryption-keyfalsefalsefalse", + "Date" : "Fri, 20 Dec 2019 23:44:20 GMT", + "x-ms-client-request-id" : "833f516e-de8c-4c85-b5d7-4a2cf61224af", + "Content-Type" : "application/xml" + }, + "Exception" : null + }, { + "Method" : "DELETE", + "Uri" : "https://gaprastg71.blob.core.windows.net/jtcdownloadtofileexistssucceeds087572dd477056d04a4?restype=container", + "Headers" : { + "x-ms-version" : "2019-02-02", + "User-Agent" : "azsdk-java-azure-storage-blob/12.2.0-beta.2 (11.0.4; Windows 10 10.0)", + "x-ms-client-request-id" : "574fcc77-94cc-479d-8cb5-bc7a7b56731b" + }, + "Response" : { + "x-ms-version" : "2019-02-02", + "Server" : "Windows-Azure-Blob/1.0 Microsoft-HTTPAPI/2.0", + "retry-after" : "0", + "Content-Length" : "0", + "StatusCode" : "202", + "x-ms-request-id" : "bfd6dd16-001e-0029-0a8f-b7ac4f000000", + "Date" : "Fri, 20 Dec 2019 23:44:21 GMT", + "x-ms-client-request-id" : "574fcc77-94cc-479d-8cb5-bc7a7b56731b" + }, + "Exception" : null + } ], + "variables" : [ "jtcdownloadtofileexistssucceeds087572dd477056d04a4", "javablobdownloadtofileexistssucceeds107956e96a6f95a8" ] +} \ No newline at end of file diff --git a/sdk/storage/azure-storage-common/CHANGELOG.md b/sdk/storage/azure-storage-common/CHANGELOG.md index 92aa2bd426f30..637418d72e3d8 100644 --- a/sdk/storage/azure-storage-common/CHANGELOG.md +++ b/sdk/storage/azure-storage-common/CHANGELOG.md @@ -1,6 +1,6 @@ # Release History -## 12.2.0-beta.2 (Unreleased) +## 12.2.0 (2020-01-08) ## 12.2.0-beta.1 (2019-12-18) - Added generateSas methods on service clients to improve discoverability and convenience of sas. Deprecated setters of required parameters, generateSasQueryParameters methods on AccountSasSignatureValues to direct users to using the methods added on clients. diff --git a/sdk/storage/azure-storage-common/pom.xml b/sdk/storage/azure-storage-common/pom.xml index fd21c5b3c90d4..d43bad68aeca8 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.2.0-beta.2 + 12.2.0 Microsoft Azure common module for Storage This module contains common code based for all Microsoft Azure Storage client libraries. @@ -36,7 +36,7 @@ com.azure azure-core - 1.1.0 + 1.2.0 org.slf4j @@ -46,7 +46,7 @@ com.azure azure-core-http-netty - 1.1.0 + 1.2.0 + 1.1.0 test com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/StorageOutputStream.java b/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/StorageOutputStream.java index cdeb0a129e81b..78a7c6e0bf8b3 100644 --- a/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/StorageOutputStream.java +++ b/sdk/storage/azure-storage-common/src/main/java/com/azure/storage/common/StorageOutputStream.java @@ -42,7 +42,7 @@ protected StorageOutputStream(final int writeThreshold) { * @param offset An int which represents the start offset in the data. * @param length An int which represents the number of bytes to write. */ - private void writeInternal(final byte[] data, int offset, int length) { + protected void writeInternal(final byte[] data, int offset, int length) { int chunks = (int) (Math.ceil((double) length / (double) this.writeThreshold)); Flux.range(0, chunks).map(c -> offset + c * this.writeThreshold) .concatMap(pos -> processChunk(data, pos, offset, length)) @@ -125,7 +125,7 @@ public void write(@NonNull final byte[] data, final int offset, final int length *

* true is acceptable for you. * - * @param byteVal An int which represents the bye value to write. + * @param byteVal An int which represents the byte value to write. */ @Override public void write(final int byteVal) { diff --git a/sdk/storage/azure-storage-file-datalake/CHANGELOG.md b/sdk/storage/azure-storage-file-datalake/CHANGELOG.md index 1d276bcfb60c1..5ad886b9a8fd2 100644 --- a/sdk/storage/azure-storage-file-datalake/CHANGELOG.md +++ b/sdk/storage/azure-storage-file-datalake/CHANGELOG.md @@ -1,6 +1,10 @@ # Release History -## 12.0.0-beta.9 (Unreleased) +## 12.0.0-beta.9 (2020-01-08) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-file-datalake_12.0.0-beta.9/sdk/storage/azure-storage-file-datalake/README.md) +and +[samples](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-file-datalake_12.0.0-beta.9/sdk/storage/azure-storage-file-datalake/src/samples/java/com/azure/storage/file/datalake) ## 12.0.0-beta.8 (2019-12-18) - Added SAS generation methods on clients to improve discoverability and convenience of sas. diff --git a/sdk/storage/azure-storage-file-datalake/pom.xml b/sdk/storage/azure-storage-file-datalake/pom.xml index 5099f03456f5f..6d2bde56e54f9 100644 --- a/sdk/storage/azure-storage-file-datalake/pom.xml +++ b/sdk/storage/azure-storage-file-datalake/pom.xml @@ -55,12 +55,12 @@ com.azure azure-storage-blob - 12.2.0-beta.2 + 12.2.0 com.azure azure-core - 1.1.0 + 1.2.0 + 1.1.0 test com.azure azure-core-http-netty - 1.1.0 + 1.2.0 test @@ -106,7 +106,7 @@ com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/DataLakeFileSystemAsyncClient.java b/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/DataLakeFileSystemAsyncClient.java index 88d6ab9cf0a21..770d699f8cb3c 100644 --- a/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/DataLakeFileSystemAsyncClient.java +++ b/sdk/storage/azure-storage-file-datalake/src/main/java/com/azure/storage/file/datalake/DataLakeFileSystemAsyncClient.java @@ -15,6 +15,7 @@ import com.azure.core.util.logging.ClientLogger; import com.azure.storage.blob.BlobContainerAsyncClient; import com.azure.storage.blob.specialized.BlockBlobAsyncClient; +import com.azure.storage.common.StorageSharedKeyCredential; import com.azure.storage.common.Utility; import com.azure.storage.common.implementation.StorageImplUtils; import com.azure.storage.file.datalake.implementation.DataLakeStorageClientBuilder; diff --git a/sdk/storage/azure-storage-file-datalake/src/test/java/com/azure/storage/file/datalake/APISpec.groovy b/sdk/storage/azure-storage-file-datalake/src/test/java/com/azure/storage/file/datalake/APISpec.groovy index de45e7a54c5c8..eb705adca0aa7 100644 --- a/sdk/storage/azure-storage-file-datalake/src/test/java/com/azure/storage/file/datalake/APISpec.groovy +++ b/sdk/storage/azure-storage-file-datalake/src/test/java/com/azure/storage/file/datalake/APISpec.groovy @@ -128,6 +128,9 @@ class APISpec extends Specification { this.interceptorManager = new InterceptorManager(className + fullTestName, testMode) this.resourceNamer = new TestResourceNamer(className + testName, testMode, interceptorManager.getRecordedData()) + // Print out the test name to create breadcrumbs in our test logging in case anything hangs. + System.out.printf("========================= %s.%s =========================%n", className, fullTestName) + // If the test doesn't have the Requires tag record it in live mode. recordLiveMode = specificationContext.getCurrentIteration().getDescription().getAnnotation(Requires.class) == null diff --git a/sdk/storage/azure-storage-file-datalake/src/test/java/com/azure/storage/file/datalake/SASTest.groovy b/sdk/storage/azure-storage-file-datalake/src/test/java/com/azure/storage/file/datalake/SASTest.groovy index be254e0278fcb..16b0ec99f58cf 100644 --- a/sdk/storage/azure-storage-file-datalake/src/test/java/com/azure/storage/file/datalake/SASTest.groovy +++ b/sdk/storage/azure-storage-file-datalake/src/test/java/com/azure/storage/file/datalake/SASTest.groovy @@ -4,7 +4,6 @@ package com.azure.storage.file.datalake import com.azure.storage.blob.BlobServiceVersion -import com.azure.storage.blob.models.BlobStorageException import com.azure.storage.blob.implementation.util.BlobSasImplUtil import com.azure.storage.common.implementation.Constants import com.azure.storage.common.sas.* @@ -17,7 +16,6 @@ import com.azure.storage.file.datalake.models.UserDelegationKey import com.azure.storage.file.datalake.sas.DataLakeServiceSasSignatureValues import com.azure.storage.file.datalake.sas.FileSystemSasPermission import com.azure.storage.file.datalake.sas.PathSasPermission -import spock.lang.Requires import spock.lang.Unroll import java.time.LocalDateTime diff --git a/sdk/storage/azure-storage-file-share/CHANGELOG.md b/sdk/storage/azure-storage-file-share/CHANGELOG.md index 4a4ffb18bb158..97ff0070ce623 100644 --- a/sdk/storage/azure-storage-file-share/CHANGELOG.md +++ b/sdk/storage/azure-storage-file-share/CHANGELOG.md @@ -1,12 +1,18 @@ # Release History -## 12.1.0-beta.2 (Unreleased) +## 12.2.0-beta.1 (Unreleased) - Added support for the 2019-07-07 service version. - Added support for file leases. Includes adding the ShareLeaseClientBuilder, ShareLeaseClient, and ShareLeaseAsync client and overloads accepting leaseIds for operations that support leases. - Added failedClosedHandles property to CloseHandlesInfo to allow users to access number of failed handles in forceCloseAllHandles and closeHandle. - Added support for obtaining premium file properties in ShareServiceClient.listShares and ShareClient.getProperties. - Added support for additional start copy parameters - FileSmbProperties, file permission, file permission copy mode, set archive and ignore read only. +## 12.1.0 (2020-01-08) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-file_12.1.0/sdk/storage/azure-storage-file-share/README.md) +and +[samples](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-file_12.1.0/sdk/storage/azure-storage-file-share/src/samples/java/com/azure/storage/file/share) + ## 12.1.0-beta.1 (2019-12-18) - Added SAS generation methods on clients to improve discoverability and convenience of sas. Deprecated setFilePath, setShareName generateSasQueryParameters methods on ShareServiceSasSignatureValues to direct users to using the methods added on clients. diff --git a/sdk/storage/azure-storage-file-share/README.md b/sdk/storage/azure-storage-file-share/README.md index 1ff0b4733fab2..b1172af3cc5b5 100644 --- a/sdk/storage/azure-storage-file-share/README.md +++ b/sdk/storage/azure-storage-file-share/README.md @@ -24,7 +24,7 @@ Shares provide a way to organize sets of files and also can be mounted as an SMB com.azure azure-storage-file-share - 12.1.0-beta.2 + 12.1.0 ``` [//]: # ({x-version-update-end}) @@ -43,7 +43,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-storage-file-share - 12.1.0-beta.2 + 12.1.0 com.azure diff --git a/sdk/storage/azure-storage-file-share/pom.xml b/sdk/storage/azure-storage-file-share/pom.xml index 0200e038a2694..02d34af96854c 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.1.0-beta.2 + 12.1.0 Microsoft Azure client library for File Share Storage This module contains client library for Microsoft Azure File Share Storage. @@ -40,12 +40,12 @@ com.azure azure-core - 1.1.0 + 1.2.0 com.azure azure-storage-common - 12.2.0-beta.2 + 12.2.0 + 1.1.0 test com.azure azure-core-http-netty - 1.1.0 + 1.2.0 test 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 1009135f75ae3..6323d30ec8bc6 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 @@ -103,15 +103,6 @@ public String getShareUrl() { return shareUrlString.toString(); } - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - public HttpPipeline getHttpPipeline() { - return azureFileStorageClient.getHttpPipeline(); - } - /** * Gets the service version the client is using. * @@ -1101,6 +1092,15 @@ public String getAccountName() { return this.accountName; } + /** + * Gets the {@link HttpPipeline} powering this client. + * + * @return The pipeline. + */ + public HttpPipeline getHttpPipeline() { + return azureFileStorageClient.getHttpPipeline(); + } + /** * Generates a service sas for the queue using the specified {@link ShareServiceSasSignatureValues} * Note : The client must be authenticated via {@link StorageSharedKeyCredential} diff --git a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareClient.java b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareClient.java index 7055f29352ff8..cdedd0b5cc0a2 100644 --- a/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareClient.java +++ b/sdk/storage/azure-storage-file-share/src/main/java/com/azure/storage/file/share/ShareClient.java @@ -67,15 +67,6 @@ public ShareServiceVersion getServiceVersion() { return client.getServiceVersion(); } - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - public HttpPipeline getHttpPipeline() { - return client.getHttpPipeline(); - } - /** * Constructs a {@link ShareDirectoryClient} that interacts with the root directory in the share. * @@ -893,6 +884,15 @@ public String getAccountName() { return this.client.getAccountName(); } + /** + * Gets the {@link HttpPipeline} powering this client. + * + * @return The pipeline. + */ + public HttpPipeline getHttpPipeline() { + return this.client.getHttpPipeline(); + } + /** * Generates a service sas for the queue using the specified {@link ShareServiceSasSignatureValues} * Note : The client must be authenticated via {@link StorageSharedKeyCredential} 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 cbfd5cd54890c..03b9cf1351734 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 @@ -158,15 +158,6 @@ public ShareServiceVersion getServiceVersion() { return serviceVersion; } - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - public HttpPipeline getHttpPipeline() { - return azureFileStorageClient.getHttpPipeline(); - } - /** * Creates a file in the storage account and returns a response of {@link ShareFileInfo} to interact with it. * @@ -1771,6 +1762,15 @@ public String getAccountName() { return this.accountName; } + /** + * Gets the {@link HttpPipeline} powering this client. + * + * @return The pipeline. + */ + public HttpPipeline getHttpPipeline() { + return azureFileStorageClient.getHttpPipeline(); + } + /** * Generates a service SAS for the file using the specified {@link ShareServiceSasSignatureValues} * Note : The client must be authenticated via {@link StorageSharedKeyCredential} 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 0c67f420dd96e..c5c514cf18dad 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 @@ -88,15 +88,6 @@ public ShareServiceVersion getServiceVersion() { return shareFileAsyncClient.getServiceVersion(); } - /** - * Gets the {@link HttpPipeline} powering this client. - * - * @return The pipeline. - */ - public HttpPipeline getHttpPipeline() { - return this.shareFileAsyncClient.getHttpPipeline(); - } - /** * Opens a file input stream to download the file. *

@@ -1384,6 +1375,15 @@ public String getAccountName() { return this.shareFileAsyncClient.getAccountName(); } + /** + * Gets the {@link HttpPipeline} powering this client. + * + * @return The pipeline. + */ + public HttpPipeline getHttpPipeline() { + return this.shareFileAsyncClient.getHttpPipeline(); + } + /** * Generates a service SAS for the file using the specified {@link ShareServiceSasSignatureValues} * Note : The client must be authenticated via {@link StorageSharedKeyCredential} diff --git a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/APISpec.groovy b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/APISpec.groovy index 84df02d317543..bd1afc2d54a37 100644 --- a/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/APISpec.groovy +++ b/sdk/storage/azure-storage-file-share/src/test/java/com/azure/storage/file/share/APISpec.groovy @@ -38,7 +38,6 @@ class APISpec extends Specification { URL testFolder = getClass().getClassLoader().getResource("testfiles") InterceptorManager interceptorManager TestResourceNamer testResourceName - // Prefixes for paths and shares String sharePrefix = "jts" // java test share @@ -100,6 +99,9 @@ class APISpec extends Specification { } premiumFileServiceClient = setClient(premiumCredential) premiumFileServiceAsyncClient = setAsyncClient(premiumCredential) + + // Print out the test name to create breadcrumbs in our test logging in case anything hangs. + System.out.printf("========================= %s.%s =========================%n", className, testName) } /** @@ -221,6 +223,23 @@ class APISpec extends Specification { return getServiceClientBuilder(credential, endpoint, policies).buildClient() } + def fileServiceBuilderHelper(final InterceptorManager interceptorManager) { + ShareServiceClientBuilder shareServiceClientBuilder = new ShareServiceClientBuilder(); + if (testMode != TestMode.PLAYBACK) { + if (testMode == TestMode.RECORD) { + shareServiceClientBuilder.addPolicy(interceptorManager.getRecordPolicy()); + } + return shareServiceClientBuilder + .connectionString(connectionString) + .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) + .httpClient(getHttpClient()) + } else { + return shareServiceClientBuilder + .connectionString(connectionString) + .httpClient(interceptorManager.getPlaybackClient()) + } + } + ShareServiceClientBuilder getServiceClientBuilder(StorageSharedKeyCredential credential, String endpoint, HttpPipelinePolicy... policies) { ShareServiceClientBuilder builder = new ShareServiceClientBuilder() @@ -232,7 +251,7 @@ class APISpec extends Specification { builder.addPolicy(policy) } - if (testMode == TestMode.RECORD) { + if (!liveMode()) { builder.addPolicy(interceptorManager.getRecordPolicy()) } @@ -243,23 +262,6 @@ class APISpec extends Specification { return builder } - def fileServiceBuilderHelper(final InterceptorManager interceptorManager) { - ShareServiceClientBuilder shareServiceClientBuilder = new ShareServiceClientBuilder(); - if (testMode != TestMode.PLAYBACK) { - if (testMode == TestMode.RECORD) { - shareServiceClientBuilder.addPolicy(interceptorManager.getRecordPolicy()); - } - return shareServiceClientBuilder - .connectionString(connectionString) - .httpLogOptions(new HttpLogOptions().setLogLevel(HttpLogDetailLevel.BODY_AND_HEADERS)) - .httpClient(getHttpClient()) - } else { - return shareServiceClientBuilder - .connectionString(connectionString) - .httpClient(interceptorManager.getPlaybackClient()) - } - } - ShareClientBuilder getShareClientBuilder(String endpoint) { ShareClientBuilder builder = new ShareClientBuilder() .endpoint(endpoint) @@ -363,7 +365,7 @@ class APISpec extends Specification { HttpClient getHttpClient() { NettyAsyncHttpClientBuilder builder = new NettyAsyncHttpClientBuilder() - if (testMode == TestMode.RECORD || testMode == TestMode.LIVE) { + if (testMode != TestMode.PLAYBACK) { builder.wiretap(true) if (Boolean.parseBoolean(Configuration.getGlobalConfiguration().get("AZURE_TEST_DEBUGGING"))) { diff --git a/sdk/storage/azure-storage-queue/CHANGELOG.md b/sdk/storage/azure-storage-queue/CHANGELOG.md index 25f0ce1545eb8..7cd078f033eea 100644 --- a/sdk/storage/azure-storage-queue/CHANGELOG.md +++ b/sdk/storage/azure-storage-queue/CHANGELOG.md @@ -1,6 +1,10 @@ # Release History -## 12.2.0-beta.2 (Unreleased) +## 12.2.0 (2020-01-08) +This package's +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-queue_12.2.0/sdk/storage/azure-storage-file-queue/README.md) +and +[samples](https://github.com/Azure/azure-sdk-for-java/blob/azure-storage-queue_12.2.0/sdk/storage/azure-storage-file-queue/src/samples/java/com/azure/storage/queue) ## 12.2.0-beta.1 (2019-12-18) - Added SAS generation methods on clients to improve discoverability and convenience of sas. Deprecated setQueueName, generateSasQueryParameters methods on QueueServiceSasSignatureValues to direct users to using the methods added on clients. diff --git a/sdk/storage/azure-storage-queue/README.md b/sdk/storage/azure-storage-queue/README.md index 618569a99caba..a39995d2739d7 100644 --- a/sdk/storage/azure-storage-queue/README.md +++ b/sdk/storage/azure-storage-queue/README.md @@ -20,7 +20,7 @@ A single queue message can be up to 64 KB in size, and a queue can contain milli com.azure azure-storage-queue - 12.2.0-beta.2 + 12.2.0 ``` [//]: # ({x-version-update-end}) @@ -38,7 +38,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-storage-queue - 12.2.0-beta.2 + 12.2.0 com.azure diff --git a/sdk/storage/azure-storage-queue/pom.xml b/sdk/storage/azure-storage-queue/pom.xml index f5f8370861968..b6779c975a02c 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.2.0-beta.2 + 12.2.0 Microsoft Azure client library for Queue Storage This module contains client library for Microsoft Azure Queue Storage. @@ -36,23 +36,23 @@ com.azure azure-core - 1.1.0 + 1.2.0 com.azure azure-storage-common - 12.2.0-beta.2 + 12.2.0 com.azure azure-core-test - 1.1.0-beta.2 + 1.1.0 test com.azure azure-core-http-netty - 1.1.0 + 1.2.0 test @@ -77,7 +77,7 @@ com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/storage/azure-storage-queue/src/test/java/com/azure/storage/queue/APISpec.groovy b/sdk/storage/azure-storage-queue/src/test/java/com/azure/storage/queue/APISpec.groovy index 13cfa91e905c4..20a17e87c7318 100644 --- a/sdk/storage/azure-storage-queue/src/test/java/com/azure/storage/queue/APISpec.groovy +++ b/sdk/storage/azure-storage-queue/src/test/java/com/azure/storage/queue/APISpec.groovy @@ -58,6 +58,9 @@ class APISpec extends Specification { connectionString = "DefaultEndpointsProtocol=https;AccountName=teststorage;AccountKey=atestaccountkey;" + "EndpointSuffix=core.windows.net" } + + // Print out the test name to create breadcrumbs in our test logging in case anything hangs. + System.out.printf("========================= %s.%s =========================%n", className, testName) } /** @@ -178,7 +181,6 @@ class APISpec extends Specification { return builder } - private def refactorName(String text) { def fullName = text.split(" ").collect { it.capitalize() }.join("") def matcher = (fullName =~ /(.*)(\[)(.*)(\])/) diff --git a/sdk/template/azure-sdk-template/CHANGELOG.md b/sdk/template/azure-sdk-template/CHANGELOG.md new file mode 100644 index 0000000000000..82d3974cdc205 --- /dev/null +++ b/sdk/template/azure-sdk-template/CHANGELOG.md @@ -0,0 +1,14 @@ +# Release History + +## 1.0.4-beta.1 (2019-11-20) + +## Version 1.0.3 (2019-11-18) + +## Version 1.0.3-beta.1 (2019-11-17) + +## Version 1.0.1 (2019-11-17) + +## Version 1.0.1-beta.1 (2019-11-17) + +## Version 1.0.2 (2019-08-15) +- Initial release. Please see the README and wiki for information on the new design. diff --git a/sdk/template/azure-sdk-template/pom.xml b/sdk/template/azure-sdk-template/pom.xml index d61131d1e5f99..d6b77e1339a39 100644 --- a/sdk/template/azure-sdk-template/pom.xml +++ b/sdk/template/azure-sdk-template/pom.xml @@ -31,7 +31,7 @@ com.azure azure-core - 1.1.0 + 1.2.0 junit diff --git a/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md index 3c3d47dc2d7b5..baa9b42aca21b 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md +++ b/sdk/textanalytics/azure-ai-textanalytics/CHANGELOG.md @@ -3,14 +3,12 @@ ## 1.0.0-beta.1 (Unreleased) For details on the Azure SDK for Java (January 2020 Preview) release refer to the [release announcement](). - -### Added - Initial release of this module. -- Support for subscription key and AAD authentication for both synchronous and asynchronous clients. +- Added support for subscription key and AAD authentication for both synchronous and asynchronous clients. - Added Detect Language, Recognize Entity, Recognize PII entity, Recognize Linking Entity, Analyze Sentiment APIs. This package's -[documentation]() +[documentation](https://github.com/Azure/azure-sdk-for-java/blob/azure-ai-textanalytics_1.0.0-beta.1/sdk/textanalytics/azure-ai-textanalytics/README.md) and -[samples]() +[samples](https://github.com/Azure/azure-sdk-for-java/blob/azure-ai-textanalytics_1.0.0-beta.1/sdk/textanalytics/azure-ai-textanalytics/src/samples) demonstrate the new API. diff --git a/sdk/textanalytics/azure-ai-textanalytics/README.md b/sdk/textanalytics/azure-ai-textanalytics/README.md index 3658bd1bc0b8a..711a040dfcd03 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/README.md +++ b/sdk/textanalytics/azure-ai-textanalytics/README.md @@ -1,11 +1,15 @@ # Azure Text Analytics client library for Java Text Analytics is a cloud-based service that provides advanced natural language processing over raw text, -and includes four main functions: +and includes six main functions: -- Sentiment Analysis -- Named Entity Recognition - Language Detection +- Sentiment Analysis - Key Phrase Extraction +- Named Entity Recognition +- Recognition of Personally Identifiable Information +- Linked Entity Recognition + +[Source code][source_code] | [Package (Maven)][package] | [API reference documentation][api_reference_doc] | [Product Documentation][product_documentation] | [Samples][samples_readme] ## Getting started @@ -35,7 +39,7 @@ Text Analytics to use Netty HTTP client. com.azure azure-core-http-netty - 1.1.0 + 1.2.0 ``` [//]: # ({x-version-update-end}) @@ -67,7 +71,7 @@ Netty and include OkHTTP client in your pom.xml. com.azure azure-core-http-okhttp - 1.1.0-beta.1 + 1.1.0 ``` [//]: # ({x-version-update-end}) @@ -77,6 +81,7 @@ When an HTTP client is included on the classpath, as shown above, it is not nece For starters, by having the Netty or OkHTTP dependencies on your classpath, as shown above, you can create new instances of these `HttpClient` types using their builder APIs. For example, here is how you would create a Netty HttpClient instance: + ```java HttpClient client = new NettyAsyncHttpClientBuilder() .port(8080) @@ -113,7 +118,7 @@ az cognitiveservices account create \ --yes ``` ### Authenticate the client -In order to interact with the Text Analytics service, you'll need to create an instance of the [TextAnalyticsClient](#create-ta-client) class. You would need an **endpoint** and **subscription key** to instantiate a client object. +In order to interact with the Text Analytics service, you'll need to create an instance of the [TextAnalyticsClient](#create-a-client) class. You would need an **endpoint** and **subscription key** to instantiate a client object. #### Get credentials ##### Types of credentials @@ -125,13 +130,16 @@ cognitive services. provide the key as a string. This can be found in the Azure Portal under the "Quickstart" section or by running the following Azure CLI command: - ```az cognitiveservices account keys list --name "resource-name" --resource-group "resource-group-name"``` + ```bash + az cognitiveservices account keys list --name "resource-name" --resource-group "resource-group-name" + ``` Use the key as the credential parameter to authenticate the client: + ```java - TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) .buildClient(); ``` @@ -154,11 +162,12 @@ cognitive services. AZURE_CLIENT_ID, AZURE_TENANT_ID, AZURE_CLIENT_SECRET Use the returned token credential to authenticate the client: + ```java - TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .endpoint("https://servicename.cognitiveservices.azure.com/") - .credential(new DefaultAzureCredentialBuilder().build()) - .buildClient(); + TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .endpoint(ENDPOINT) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); ``` #### Create a Client @@ -167,16 +176,38 @@ analyze sentiment, recognize entities, detect language, and extract key phrases To create a client object, you will need the cognitive services or text analytics endpoint to your resource and a subscription key that allows you access: + ```java -// Instantiate a client that will be used to call the service. -TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") +TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) .buildClient(); ``` ## Key concepts +### Text Input +A text input, sometimes called a `document`, is a single unit of input to be analyzed by the predictive models +in the Text Analytics service. Operations on Text Analytics client may take a single text input or a collection +of inputs to be analyzed as a batch. + +### Operation Result +An operation result, such as `AnalyzeSentimentResult`, is the result of a Text Analytics operation, containing a +prediction or predictions about a single text input. An operation's result type also may optionally include information +about the input document and how it was processed. + +### Operation Result Collection +An operation result collection, such as `DocumentResultCollection`, which is the collection of +the result of a Text Analytics analyzing sentiment operation. `DocumentResultCollection` includes the model version of +the operation and statistics of the batch documents. Since `DocumentResultCollection` extends `IterableStream`, +the list of item can be retrieved by streaming or iterating the list. + +### Operation Overloads +For each supported operation, the Text Analytics client provides method overloads to take a single text input, a batch +of text inputs as strings, or a batch of either `TextDocumentInput` or `DetectLanguageInput` objects. The overload +taking the `TextDocumentInput` or `DetectLanguageInput` batch allows callers to give each document a unique ID, or +indicate that the documents in the batch are written in different languages. + The following are types of text analysis that the service offers: 1. [Sentiment Analysis](https://docs.microsoft.com/azure/cognitive-services/text-analytics/how-tos/text-analytics-how-to-sentiment-analysis) @@ -210,37 +241,40 @@ The following are types of text analysis that the service offers: See [Language and regional support](https://docs.microsoft.com/azure/cognitive-services/text-analytics/language-support) for what is currently available for each operation. +## Examples +The following sections provide several code snippets covering some of the most common text analytics tasks, including: + ### Text Analytics Client +Text analytics support both synchronous and asynchronous client creation by using +`TextAnalyticsClientBuilder`, + + ``` java -TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") +TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) .buildClient(); ``` - + ``` java -TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") +TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) .buildAsyncClient(); ``` -## Examples -The following sections provide several code snippets covering some of the most common text analytics tasks, including: - ### Detect language -Detect language in a batch of documents. - + ```java -TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") - .buildAsyncClient(); +TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildClient(); String inputText = "Bonjour tout le monde"; -for(DetectedLanguage detectedLanguage : client.detectLanguage(text, "US").getDetectedLanguages()) { - System.out.printf("Other detected languages: %s, ISO 6391 Name: %s, Score: %s.%n", +for (DetectedLanguage detectedLanguage : textAnalyticsClient.detectLanguage(inputText).getDetectedLanguages()) { + System.out.printf("Detected languages name: %s, ISO 6391 Name: %s, Score: %s.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); @@ -248,76 +282,80 @@ for(DetectedLanguage detectedLanguage : client.detectLanguage(text, "US").getDet ``` ### Recognize entity + ```java -TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") +TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) .buildClient(); String text = "Satya Nadella is the CEO of Microsoft"; -for (NamedEntity entity : client.recognizeEntities(text).getNamedEntities()) { +for (NamedEntity entity : textAnalyticsClient.recognizeEntities(text).getNamedEntities()) { System.out.printf( - "Recognized NamedEntity: %s, Type: %s, Subtype: %s, Score: %s.%n", + "Recognized Named Entity: %s, Type: %s, Subtype: %s, Score: %s.%n", entity.getText(), entity.getType(), entity.getSubtype(), - entity.getOffset(), - entity.getLength(), entity.getScore()); } ``` ### Recognize PII(Personally Identifiable Information) entity + ```java -TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") +TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) .buildClient(); // The text that need be analysed. String text = "My SSN is 555-55-5555"; -for (NamedEntity entity : client.recognizePiiEntities(text).getNamedEntities()) { +for (NamedEntity entity : textAnalyticsClient.recognizePiiEntities(text).getNamedEntities()) { System.out.printf( "Recognized PII Entity: %s, Type: %s, Subtype: %s, Score: %s.%n", entity.getText(), entity.getType(), entity.getSubtype(), - entity.getScore())); + entity.getScore()); } ``` ### Recognize linked entity + + ```java -TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") +TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) .buildClient(); // The text that need be analysed. String text = "Old Faithful is a geyser at Yellowstone Park."; -for (LinkedEntity linkedEntity : client.recognizeLinkedEntities(text).getLinkedEntities()) { - System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s.%n", +for (LinkedEntity linkedEntity : textAnalyticsClient.recognizeLinkedEntities(text).getLinkedEntities()) { + System.out.printf("Recognized Linked Entity: %s, Url: %s, Data Source: %s.%n", linkedEntity.getName(), - linkedEntity.getUri(), + linkedEntity.getUrl(), linkedEntity.getDataSource()); } ``` ### Analyze sentiment + + ```java -TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") +TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) .buildClient(); String text = "The hotel was dark and unclean."; -for (TextSentiment textSentiment : client.analyzeSentiment(text).getSentenceSentiments()) { +for (TextSentiment textSentiment : textAnalyticsClient.analyzeSentiment(text).getSentenceSentiments()) { System.out.printf( - "Recognized Sentence TextSentiment: %s.%n", + "Analyzed Sentence Sentiment class: %s.%n", textSentiment.getTextSentimentClass()); } ``` @@ -338,10 +376,13 @@ This project has adopted the [Microsoft Open Source Code of Conduct][coc]. For m [azure_subscription]: https://azure.microsoft.com/free +[api_reference_doc]: https://azure.github.io/azure-sdk-for-java/textanalytics.html [cla]: https://cla.microsoft.com [coc]: https://opensource.microsoft.com/codeofconduct/ [coc_faq]: https://opensource.microsoft.com/codeofconduct/faq/ [coc_contact]: mailto:opencode@microsoft.com +[package]: https://mvnrepository.com/artifact/com.azure/azure-ai-textanalytics +[product_documentation]: https://docs.microsoft.com/azure/cognitive-services/text-analytics/overview [samples_readme]: src/samples/README.md [source_code]: src diff --git a/sdk/textanalytics/azure-ai-textanalytics/pom.xml b/sdk/textanalytics/azure-ai-textanalytics/pom.xml index 46602c601baf8..80723741c449a 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/pom.xml +++ b/sdk/textanalytics/azure-ai-textanalytics/pom.xml @@ -36,14 +36,14 @@ com.azure azure-core-http-netty - 1.1.0 + 1.2.0 com.azure azure-core-test - 1.1.0-beta.1 + 1.1.0 test @@ -52,10 +52,16 @@ 5.4.2 test + + org.junit.jupiter + junit-jupiter-engine + 5.4.2 + test + com.azure azure-identity - 1.0.1 + 1.0.2 test diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/AnalyzeSentimentAsyncClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/AnalyzeSentimentAsyncClient.java new file mode 100644 index 0000000000000..6c3afcff0eafd --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/AnalyzeSentimentAsyncClient.java @@ -0,0 +1,159 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl; +import com.azure.ai.textanalytics.implementation.models.DocumentError; +import com.azure.ai.textanalytics.implementation.models.DocumentSentiment; +import com.azure.ai.textanalytics.implementation.models.MultiLanguageBatchInput; +import com.azure.ai.textanalytics.implementation.models.SentimentConfidenceScorePerLabel; +import com.azure.ai.textanalytics.implementation.models.SentimentResponse; +import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.ai.textanalytics.models.TextSentiment; +import com.azure.ai.textanalytics.models.TextSentimentClass; +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 reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import static com.azure.ai.textanalytics.Transforms.mapByIndex; +import static com.azure.ai.textanalytics.Transforms.toBatchStatistics; +import static com.azure.ai.textanalytics.Transforms.toMultiLanguageInput; +import static com.azure.ai.textanalytics.Transforms.toTextAnalyticsError; +import static com.azure.ai.textanalytics.Transforms.toTextDocumentStatistics; + +/** + * Helper class for managing sentiment analysis endpoint. + */ +class AnalyzeSentimentAsyncClient { + private final ClientLogger logger = new ClientLogger(AnalyzeSentimentAsyncClient.class); + private final TextAnalyticsClientImpl service; + + /** + * Create a {@code AnalyzeSentimentAsyncClient} that sends requests to the Text Analytics services's sentiment + * analysis endpoint. + * + * @param service The proxy service used to perform REST calls. + */ + AnalyzeSentimentAsyncClient(TextAnalyticsClientImpl service) { + this.service = service; + } + + Mono> analyzeSentimentWithResponse(String text, String language, Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return analyzeBatchSentimentWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + Mono>> analyzeSentimentWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + return analyzeBatchSentimentWithResponse(documentInputs, null, context); + } + + Mono>> analyzeBatchSentimentWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(toMultiLanguageInput(textInputs)); + return service.sentimentWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of text sentiment input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of text sentiment output - {}", response)) + .doOnError(error -> logger.warning("Failed to analyze text sentiment - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + /** + * Helper method to convert the service response of {@link SentimentResponse} to {@link DocumentResultCollection}. + * + * @param sentimentResponse the {@link SentimentResponse} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link AnalyzeSentimentResult} to be returned by the SDK. + */ + private DocumentResultCollection toDocumentResultCollection( + final SentimentResponse sentimentResponse) { + List analyzeSentimentResults = new ArrayList<>(); + for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { + analyzeSentimentResults.add(convertToTextSentimentResult(documentSentiment)); + } + for (DocumentError documentError : sentimentResponse.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = + toTextAnalyticsError(documentError.getError()); + analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, + error, null, null)); + } + return new DocumentResultCollection<>(analyzeSentimentResults, + sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null + : toBatchStatistics(sentimentResponse.getStatistics())); + } + + /** + * Helper method to convert the service response of {@link DocumentSentiment} to {@link AnalyzeSentimentResult}. + * + * @param documentSentiment the {@link DocumentSentiment} returned by the service. + * + * @return the {@link AnalyzeSentimentResult} to be returned by the SDK. + */ + private AnalyzeSentimentResult convertToTextSentimentResult(final DocumentSentiment documentSentiment) { + // Document text sentiment + final TextSentimentClass documentSentimentClass = TextSentimentClass.fromString(documentSentiment. + getSentiment().toString()); + if (documentSentimentClass == null) { + // Not throw exception for an invalid Sentiment type because we should not skip processing the + // other response. It is a service issue. + logger.logExceptionAsWarning( + new RuntimeException(String.format("'%s' is not valid text sentiment.", + documentSentiment.getSentiment()))); + } + final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getDocumentScores(); + + // Sentence text sentiment + final List sentenceSentimentTexts = documentSentiment.getSentences().stream() + .map(sentenceSentiment -> { + TextSentimentClass sentimentClass = TextSentimentClass.fromString(sentenceSentiment + .getSentiment().toString()); + if (sentimentClass == null) { + // Not throw exception for an invalid Sentiment type because we should not skip processing the + // other response. It is a service issue. + logger.logExceptionAsWarning( + new RuntimeException(String.format("'%s' is not valid text sentiment.", + sentenceSentiment.getSentiment()))); + } + SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getSentenceScores(); + + return new TextSentiment(sentimentClass, confidenceScorePerSentence.getNegative(), + confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive(), + sentenceSentiment.getLength(), sentenceSentiment.getOffset()); + + }).collect(Collectors.toList()); + + return new AnalyzeSentimentResult(documentSentiment.getId(), + documentSentiment.getStatistics() == null ? null + : toTextDocumentStatistics(documentSentiment.getStatistics()), null, + new TextSentiment(documentSentimentClass, confidenceScorePerLabel.getNegative(), + confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive(), + sentenceSentimentTexts.stream().mapToInt(TextSentiment::getLength).sum(), 0), + sentenceSentimentTexts); + } + +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/DetectLanguageAsyncClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/DetectLanguageAsyncClient.java new file mode 100644 index 0000000000000..af2ab897ac654 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/DetectLanguageAsyncClient.java @@ -0,0 +1,124 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl; +import com.azure.ai.textanalytics.implementation.models.DocumentError; +import com.azure.ai.textanalytics.implementation.models.DocumentLanguage; +import com.azure.ai.textanalytics.implementation.models.LanguageBatchInput; +import com.azure.ai.textanalytics.implementation.models.LanguageInput; +import com.azure.ai.textanalytics.implementation.models.LanguageResult; +import com.azure.ai.textanalytics.models.DetectLanguageInput; +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DetectedLanguage; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +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 reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import static com.azure.ai.textanalytics.Transforms.mapByIndex; + +/** + * Helper class for managing detect language endpoint. + */ +class DetectLanguageAsyncClient { + private final ClientLogger logger = new ClientLogger(DetectLanguageAsyncClient.class); + private final TextAnalyticsClientImpl service; + + /** + * Create a {@code DetectLanguageAsyncClient} that sends requests to the Text Analytics services's detect language + * endpoint. + * + * @param service The proxy service used to perform REST calls. + */ + DetectLanguageAsyncClient(TextAnalyticsClientImpl service) { + this.service = service; + } + + Mono> detectLanguageWithResponse(String text, String countryHint, Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + List languageInputs = Collections.singletonList(new DetectLanguageInput("0", + text, countryHint)); + return detectBatchLanguagesWithResponse(languageInputs, null, context).map(response -> + new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + Mono>> detectLanguagesWithResponse(List textInputs, + String countryHint, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + List detectLanguageInputs = mapByIndex(textInputs, (index, value) -> + new DetectLanguageInput(index, value, countryHint)); + + return detectBatchLanguagesWithResponse(detectLanguageInputs, null, context); + } + + Mono>> detectBatchLanguagesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final LanguageBatchInput languageBatchInput = new LanguageBatchInput() + .setDocuments(textInputs.stream().map(detectLanguageInput -> new LanguageInput() + .setId(detectLanguageInput.getId()).setText(detectLanguageInput.getText()) + .setCountryHint(detectLanguageInput.getCountryHint())).collect(Collectors.toList())); + + return service.languagesWithRestResponseAsync( + languageBatchInput, options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of language input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of detected language output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to detect languages - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + /** + * Helper method to convert the service response of {@link LanguageResult} to {@link DocumentResultCollection}. + * + * @param languageResult the {@link LanguageResult} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link DetectLanguageResult} to be returned by the SDK. + */ + private DocumentResultCollection toDocumentResultCollection( + final LanguageResult languageResult) { + + final List detectLanguageResults = new ArrayList<>(); + for (DocumentLanguage documentLanguage : languageResult.getDocuments()) { + DetectedLanguage primaryLanguage = null; + if (documentLanguage.getDetectedLanguages().size() >= 1) { + com.azure.ai.textanalytics.implementation.models.DetectedLanguage detectedLanguageResult = + documentLanguage.getDetectedLanguages().get(0); + primaryLanguage = new DetectedLanguage(detectedLanguageResult.getName(), + detectedLanguageResult.getIso6391Name(), detectedLanguageResult.getScore()); + } + detectLanguageResults.add(new DetectLanguageResult(documentLanguage.getId(), + documentLanguage.getStatistics() == null + ? null : Transforms.toTextDocumentStatistics(documentLanguage.getStatistics()), + null, + primaryLanguage, + documentLanguage.getDetectedLanguages().stream().map(detectedLanguage -> + new DetectedLanguage(detectedLanguage.getName(), detectedLanguage.getIso6391Name(), + detectedLanguage.getScore())).collect(Collectors.toList()))); + } + + for (DocumentError documentError : languageResult.getErrors()) { + com.azure.ai.textanalytics.models.TextAnalyticsError error = + Transforms.toTextAnalyticsError(documentError.getError()); + detectLanguageResults.add( + new DetectLanguageResult(documentError.getId(), null, error, null, null)); + } + + return new DocumentResultCollection<>(detectLanguageResults, languageResult.getModelVersion(), + languageResult.getStatistics() == null ? null + : Transforms.toBatchStatistics(languageResult.getStatistics())); + } + +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/ExtractKeyPhraseAsyncClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/ExtractKeyPhraseAsyncClient.java new file mode 100644 index 0000000000000..05c76b9d27167 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/ExtractKeyPhraseAsyncClient.java @@ -0,0 +1,110 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl; +import com.azure.ai.textanalytics.implementation.models.DocumentError; +import com.azure.ai.textanalytics.implementation.models.DocumentKeyPhrases; +import com.azure.ai.textanalytics.implementation.models.KeyPhraseResult; +import com.azure.ai.textanalytics.implementation.models.MultiLanguageBatchInput; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.ExtractKeyPhraseResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentInput; +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 reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; + +import static com.azure.ai.textanalytics.Transforms.mapByIndex; +import static com.azure.ai.textanalytics.Transforms.toBatchStatistics; +import static com.azure.ai.textanalytics.Transforms.toMultiLanguageInput; +import static com.azure.ai.textanalytics.Transforms.toTextAnalyticsError; +import static com.azure.ai.textanalytics.Transforms.toTextDocumentStatistics; + +/** + * Helper class for managing extract keyphrase endpoint. + */ +class ExtractKeyPhraseAsyncClient { + private final ClientLogger logger = new ClientLogger(ExtractKeyPhraseAsyncClient.class); + private final TextAnalyticsClientImpl service; + + /** + * Create a {@code ExtractKeyPhraseAsyncClient} that sends requests to the Text Analytics services's extract + * keyphrase endpoint. + * + * @param service The proxy service used to perform REST calls. + */ + ExtractKeyPhraseAsyncClient(TextAnalyticsClientImpl service) { + this.service = service; + } + + Mono> extractKeyPhrasesWithResponse(String text, String language, + Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return extractBatchKeyPhrasesWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + Mono>> extractKeyPhrasesWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + return extractBatchKeyPhrasesWithResponse(documentInputs, null, context); + } + + Mono>> extractBatchKeyPhrasesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(toMultiLanguageInput(textInputs)); + return service.keyPhrasesWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of key phrases input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to extract key phrases - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + /** + * Helper method to convert the service response of {@link KeyPhraseResult} to {@link DocumentResultCollection}. + * + * @param keyPhraseResult the {@link KeyPhraseResult} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link KeyPhraseResult} to be returned by the SDK. + */ + private DocumentResultCollection toDocumentResultCollection( + final KeyPhraseResult keyPhraseResult) { + List keyPhraseResultList = new ArrayList<>(); + for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { + keyPhraseResultList.add(new ExtractKeyPhraseResult(documentKeyPhrases.getId(), + documentKeyPhrases.getStatistics() == null ? null + : toTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, + documentKeyPhrases.getKeyPhrases())); + } + + for (DocumentError documentError : keyPhraseResult.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = + toTextAnalyticsError(documentError.getError()); + keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null, error, null)); + } + + return new DocumentResultCollection<>(keyPhraseResultList, + keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null + : toBatchStatistics(keyPhraseResult.getStatistics())); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/RecognizeEntityAsyncClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/RecognizeEntityAsyncClient.java new file mode 100644 index 0000000000000..9a12fcfb36619 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/RecognizeEntityAsyncClient.java @@ -0,0 +1,114 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl; +import com.azure.ai.textanalytics.implementation.models.DocumentEntities; +import com.azure.ai.textanalytics.implementation.models.DocumentError; +import com.azure.ai.textanalytics.implementation.models.EntitiesResult; +import com.azure.ai.textanalytics.implementation.models.MultiLanguageBatchInput; +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentInput; +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 reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import static com.azure.ai.textanalytics.Transforms.toTextAnalyticsError; +import static com.azure.ai.textanalytics.Transforms.toTextDocumentStatistics; +import static com.azure.ai.textanalytics.Transforms.toBatchStatistics; +import static com.azure.ai.textanalytics.Transforms.mapByIndex; + +/** + * Helper class for managing recognize entity endpoint. + */ +class RecognizeEntityAsyncClient { + private final ClientLogger logger = new ClientLogger(RecognizeEntityAsyncClient.class); + private final TextAnalyticsClientImpl service; + + /** + * Create a {@code RecognizeEntityAsyncClient} that sends requests to the Text Analytics services's recognize entity + * endpoint. + * + * @param service The proxy service used to perform REST calls. + */ + RecognizeEntityAsyncClient(TextAnalyticsClientImpl service) { + this.service = service; + } + + Mono> recognizeEntitiesWithResponse(String text, String language, + Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return recognizeBatchEntitiesWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + Mono>> recognizeEntitiesWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + return recognizeBatchEntitiesWithResponse(documentInputs, null, context); + } + + Mono>> recognizeBatchEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(Transforms.toMultiLanguageInput(textInputs)); + return service.entitiesRecognitionGeneralWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of named entities input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of named entities output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to recognize named entities - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + /** + * Helper method to convert the service response of {@link EntitiesResult} to {@link DocumentResultCollection}. + * + * @param entitiesResult the {@link EntitiesResult} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link DetectLanguageResult} to be returned by the SDK. + */ + private DocumentResultCollection toDocumentResultCollection( + final EntitiesResult entitiesResult) { + List recognizeEntitiesResults = new ArrayList<>(); + for (DocumentEntities documentEntities : entitiesResult.getDocuments()) { + recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentEntities.getId(), + documentEntities.getStatistics() == null ? null + : toTextDocumentStatistics(documentEntities.getStatistics()), + null, documentEntities.getEntities().stream().map(entity -> + new NamedEntity(entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), + entity.getLength(), entity.getScore())).collect(Collectors.toList()))); + } + + for (DocumentError documentError : entitiesResult.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = + toTextAnalyticsError(documentError.getError()); + recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null, error, null)); + } + + return new DocumentResultCollection<>(recognizeEntitiesResults, + entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null + : toBatchStatistics(entitiesResult.getStatistics())); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/RecognizeLinkedEntityAsyncClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/RecognizeLinkedEntityAsyncClient.java new file mode 100644 index 0000000000000..9d87ab08de674 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/RecognizeLinkedEntityAsyncClient.java @@ -0,0 +1,127 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl; +import com.azure.ai.textanalytics.implementation.models.DocumentError; +import com.azure.ai.textanalytics.implementation.models.DocumentLinkedEntities; +import com.azure.ai.textanalytics.implementation.models.EntityLinkingResult; +import com.azure.ai.textanalytics.implementation.models.LinkedEntity; +import com.azure.ai.textanalytics.implementation.models.MultiLanguageBatchInput; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.LinkedEntityMatch; +import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentInput; +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 reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import static com.azure.ai.textanalytics.Transforms.mapByIndex; +import static com.azure.ai.textanalytics.Transforms.toBatchStatistics; +import static com.azure.ai.textanalytics.Transforms.toMultiLanguageInput; +import static com.azure.ai.textanalytics.Transforms.toTextAnalyticsError; +import static com.azure.ai.textanalytics.Transforms.toTextDocumentStatistics; + +/** + * Helper class for managing recognize linked entity endpoint. + */ +class RecognizeLinkedEntityAsyncClient { + private final ClientLogger logger = new ClientLogger(RecognizeLinkedEntityAsyncClient.class); + private final TextAnalyticsClientImpl service; + + /** + * Create a {@code RecognizeLinkedEntityAsyncClient} that sends requests to the Text Analytics services's recognize + * linked entity endpoint. + * + * @param service The proxy service used to perform REST calls. + */ + RecognizeLinkedEntityAsyncClient(TextAnalyticsClientImpl service) { + this.service = service; + } + + Mono> recognizeLinkedEntitiesWithResponse(String text, String language, + Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return recognizeBatchLinkedEntitiesWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + Mono>> recognizeLinkedEntitiesWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + return recognizeBatchLinkedEntitiesWithResponse(documentInputs, null, context); + } + + Mono>> recognizeBatchLinkedEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(toMultiLanguageInput(textInputs)); + return service.entitiesLinkingWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of linked entities input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of linked entities output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to recognize linked entities - {}", error)) + .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); + } + + + private List mapLinkedEntity(List linkedEntities) { + List linkedEntitiesList = new ArrayList<>(); + for (LinkedEntity linkedEntity : linkedEntities) { + linkedEntitiesList.add(new com.azure.ai.textanalytics.models.LinkedEntity(linkedEntity.getName(), + linkedEntity.getMatches().stream().map(match -> + new LinkedEntityMatch(match.getText(), match.getScore(), match.getLength(), + match.getOffset())).collect(Collectors.toList()), linkedEntity.getLanguage(), + linkedEntity.getId(), linkedEntity.getUrl(), linkedEntity.getDataSource())); + } + return linkedEntitiesList; + } + + /** + * Helper method to convert the service response of {@link EntityLinkingResult} to {@link DocumentResultCollection}. + * + * @param entityLinkingResult the {@link EntityLinkingResult} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link RecognizeLinkedEntitiesResult} to be returned by the SDK. + */ + private DocumentResultCollection toDocumentResultCollection( + final EntityLinkingResult entityLinkingResult) { + List linkedEntitiesResults = new ArrayList<>(); + for (DocumentLinkedEntities documentLinkedEntities : entityLinkingResult.getDocuments()) { + linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentLinkedEntities.getId(), + documentLinkedEntities.getStatistics() == null ? null + : toTextDocumentStatistics(documentLinkedEntities.getStatistics()), + null, mapLinkedEntity(documentLinkedEntities.getEntities()))); + } + for (DocumentError documentError : entityLinkingResult.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = + toTextAnalyticsError(documentError.getError()); + linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentError.getId(), null, error, null)); + } + + return new DocumentResultCollection<>(linkedEntitiesResults, + entityLinkingResult.getModelVersion(), entityLinkingResult.getStatistics() == null ? null + : toBatchStatistics(entityLinkingResult.getStatistics())); + } + + +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/RecognizePiiEntityAsyncClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/RecognizePiiEntityAsyncClient.java new file mode 100644 index 0000000000000..781432dbd2c9e --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/RecognizePiiEntityAsyncClient.java @@ -0,0 +1,113 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl; +import com.azure.ai.textanalytics.implementation.models.DocumentEntities; +import com.azure.ai.textanalytics.implementation.models.DocumentError; +import com.azure.ai.textanalytics.implementation.models.EntitiesResult; +import com.azure.ai.textanalytics.implementation.models.MultiLanguageBatchInput; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.RecognizePiiEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentInput; +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 reactor.core.publisher.Mono; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Objects; +import java.util.stream.Collectors; + +import static com.azure.ai.textanalytics.Transforms.mapByIndex; +import static com.azure.ai.textanalytics.Transforms.toBatchStatistics; +import static com.azure.ai.textanalytics.Transforms.toMultiLanguageInput; +import static com.azure.ai.textanalytics.Transforms.toTextAnalyticsError; +import static com.azure.ai.textanalytics.Transforms.toTextDocumentStatistics; + +/** + * Helper class for managing recognize pii entity endpoint. + */ +class RecognizePiiEntityAsyncClient { + private final ClientLogger logger = new ClientLogger(RecognizePiiEntityAsyncClient.class); + private final TextAnalyticsClientImpl service; + + /** + * Create a {@code RecognizePiiEntityAsyncClient} that sends requests to the Text Analytics services's recognize pii + * entity endpoint. + * + * @param service The proxy service used to perform REST calls. + */ + RecognizePiiEntityAsyncClient(TextAnalyticsClientImpl service) { + this.service = service; + } + + Mono> recognizePiiEntitiesWithResponse(String text, String language, + Context context) { + Objects.requireNonNull(text, "'text' cannot be null."); + + return recognizeBatchPiiEntitiesWithResponse( + Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) + .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); + } + + Mono>> recognizePiiEntitiesWithResponse( + List textInputs, String language, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + + List documentInputs = mapByIndex(textInputs, (index, value) -> + new TextDocumentInput(index, value, language)); + return recognizeBatchPiiEntitiesWithResponse(documentInputs, null, context); + } + + Mono>> recognizeBatchPiiEntitiesWithResponse( + List textInputs, TextAnalyticsRequestOptions options, Context context) { + Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); + final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() + .setDocuments(toMultiLanguageInput(textInputs)); + return service.entitiesRecognitionPiiWithRestResponseAsync( + batchInput, + options == null ? null : options.getModelVersion(), + options == null ? null : options.showStatistics(), context) + .doOnSubscribe(ignoredValue -> logger.info("A batch of PII entities input - {}", textInputs.toString())) + .doOnSuccess(response -> logger.info("A batch of PII entities output - {}", response.getValue())) + .doOnError(error -> logger.warning("Failed to recognize PII entities - {}", error)) + .map(response -> new SimpleResponse<>(response, toPiiDocumentResultCollection(response.getValue()))); + } + + /** + * Helper method to convert the service response of {@link EntitiesResult} to {@link DocumentResultCollection}. + * + * @param entitiesResult the {@link EntitiesResult} returned by the service. + * + * @return the {@link DocumentResultCollection} of {@link RecognizePiiEntitiesResult} to be returned by the SDK. + */ + private DocumentResultCollection toPiiDocumentResultCollection( + final EntitiesResult entitiesResult) { + List recognizePiiEntitiesResults = new ArrayList<>(); + for (DocumentEntities documentEntities : entitiesResult.getDocuments()) { + recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(documentEntities.getId(), + documentEntities.getStatistics() == null ? null + : toTextDocumentStatistics(documentEntities.getStatistics()), + null, documentEntities.getEntities().stream().map(entity -> + new NamedEntity(entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), + entity.getLength(), entity.getScore())).collect(Collectors.toList()))); + } + + for (DocumentError documentError : entitiesResult.getErrors()) { + final com.azure.ai.textanalytics.models.TextAnalyticsError error = + toTextAnalyticsError(documentError.getError()); + recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null, error, null)); + } + + return new DocumentResultCollection<>(recognizePiiEntitiesResults, + entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null + : toBatchStatistics(entitiesResult.getStatistics())); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClient.java index c969f8c0d74c5..34e03ee54dd39 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClient.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClient.java @@ -4,61 +4,26 @@ package com.azure.ai.textanalytics; import com.azure.ai.textanalytics.implementation.TextAnalyticsClientImpl; -import com.azure.ai.textanalytics.implementation.models.DocumentEntities; -import com.azure.ai.textanalytics.implementation.models.DocumentError; -import com.azure.ai.textanalytics.implementation.models.DocumentKeyPhrases; -import com.azure.ai.textanalytics.implementation.models.DocumentLanguage; -import com.azure.ai.textanalytics.implementation.models.DocumentLinkedEntities; -import com.azure.ai.textanalytics.implementation.models.DocumentSentiment; -import com.azure.ai.textanalytics.implementation.models.DocumentStatistics; -import com.azure.ai.textanalytics.implementation.models.EntitiesResult; -import com.azure.ai.textanalytics.implementation.models.EntityLinkingResult; -import com.azure.ai.textanalytics.implementation.models.LanguageBatchInput; -import com.azure.ai.textanalytics.implementation.models.LanguageInput; -import com.azure.ai.textanalytics.implementation.models.LanguageResult; -import com.azure.ai.textanalytics.implementation.models.LinkedEntity; -import com.azure.ai.textanalytics.implementation.models.MultiLanguageBatchInput; -import com.azure.ai.textanalytics.implementation.models.MultiLanguageInput; -import com.azure.ai.textanalytics.implementation.models.RequestStatistics; -import com.azure.ai.textanalytics.implementation.models.SentimentConfidenceScorePerLabel; -import com.azure.ai.textanalytics.implementation.models.SentimentResponse; -import com.azure.ai.textanalytics.implementation.models.TextAnalyticsError; import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; import com.azure.ai.textanalytics.models.DetectLanguageInput; import com.azure.ai.textanalytics.models.DetectLanguageResult; -import com.azure.ai.textanalytics.models.DetectedLanguage; import com.azure.ai.textanalytics.models.DocumentResultCollection; -import com.azure.ai.textanalytics.models.ErrorCodeValue; import com.azure.ai.textanalytics.models.ExtractKeyPhraseResult; -import com.azure.ai.textanalytics.models.LinkedEntityMatch; -import com.azure.ai.textanalytics.models.NamedEntity; import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; import com.azure.ai.textanalytics.models.RecognizePiiEntitiesResult; import com.azure.ai.textanalytics.models.TextAnalyticsClientOptions; import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; -import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; import com.azure.ai.textanalytics.models.TextDocumentInput; -import com.azure.ai.textanalytics.models.TextDocumentStatistics; -import com.azure.ai.textanalytics.models.TextSentiment; -import com.azure.ai.textanalytics.models.TextSentimentClass; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; 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.FluxUtil; import com.azure.core.util.logging.ClientLogger; import reactor.core.publisher.Mono; -import java.util.ArrayList; -import java.util.Collections; import java.util.List; -import java.util.Objects; -import java.util.function.BiFunction; -import java.util.stream.Collectors; -import java.util.stream.IntStream; import static com.azure.core.util.FluxUtil.monoError; import static com.azure.core.util.FluxUtil.withContext; @@ -82,6 +47,12 @@ public final class TextAnalyticsAsyncClient { private final TextAnalyticsServiceVersion serviceVersion; private final String defaultCountryHint; private final String defaultLanguage; + final DetectLanguageAsyncClient detectLanguageAsyncClient; + final AnalyzeSentimentAsyncClient analyzeSentimentAsyncClient; + final ExtractKeyPhraseAsyncClient extractKeyPhraseAsyncClient; + final RecognizeEntityAsyncClient recognizeEntityAsyncClient; + final RecognizePiiEntityAsyncClient recognizePiiEntityAsyncClient; + final RecognizeLinkedEntityAsyncClient recognizeLinkedEntityAsyncClient; /** * Create a {@code TextAnalyticsAsyncClient} that sends requests to the Text Analytics services's endpoint. Each @@ -100,6 +71,12 @@ public final class TextAnalyticsAsyncClient { this.serviceVersion = serviceVersion; defaultCountryHint = clientOptions == null ? null : clientOptions.getDefaultCountryHint(); defaultLanguage = clientOptions == null ? null : clientOptions.getDefaultLanguage(); + this.detectLanguageAsyncClient = new DetectLanguageAsyncClient(service); + this.analyzeSentimentAsyncClient = new AnalyzeSentimentAsyncClient(service); + this.extractKeyPhraseAsyncClient = new ExtractKeyPhraseAsyncClient(service); + this.recognizeEntityAsyncClient = new RecognizeEntityAsyncClient(service); + this.recognizePiiEntityAsyncClient = new RecognizePiiEntityAsyncClient(service); + this.recognizeLinkedEntityAsyncClient = new RecognizeLinkedEntityAsyncClient(service); } /** @@ -164,20 +141,13 @@ public Mono detectLanguage(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> detectLanguageWithResponse(String text, String countryHint) { try { - return withContext(context -> detectLanguageWithResponse(text, countryHint, context)); + return withContext(context -> + detectLanguageAsyncClient.detectLanguageWithResponse(text, countryHint, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono> detectLanguageWithResponse(String text, String countryHint, Context context) { - Objects.requireNonNull(text, "'text' cannot be null."); - List languageInputs = Collections.singletonList(new DetectLanguageInput("0", - text, countryHint)); - return detectBatchLanguagesWithResponse(languageInputs, null, context).map(response -> - new SimpleResponse<>(response, response.getValue().iterator().next())); - } - /** * Returns the detected language for a batch of input. * @@ -213,21 +183,13 @@ public Mono> detectLanguages(List public Mono>> detectLanguagesWithResponse( List textInputs, String countryHint) { try { - return withContext(context -> detectLanguagesWithResponse(textInputs, countryHint, context)); + return withContext(context -> detectLanguageAsyncClient.detectLanguagesWithResponse(textInputs, countryHint, + context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono>> detectLanguagesWithResponse(List textInputs, - String countryHint, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - List detectLanguageInputs = mapByIndex(textInputs, (index, value) -> - new DetectLanguageInput(index, value, countryHint)); - - return detectBatchLanguagesWithResponse(detectLanguageInputs, null, context); - } - /** * Returns the detected language for a batch of input. * @@ -265,30 +227,12 @@ public Mono>> detectBatc List textInputs, TextAnalyticsRequestOptions options) { try { return withContext( - context -> detectBatchLanguagesWithResponse(textInputs, options, context)); + context -> detectLanguageAsyncClient.detectBatchLanguagesWithResponse(textInputs, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono>> detectBatchLanguagesWithResponse( - List textInputs, TextAnalyticsRequestOptions options, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - final LanguageBatchInput languageBatchInput = new LanguageBatchInput() - .setDocuments(textInputs.stream().map(detectLanguageInput -> new LanguageInput() - .setId(detectLanguageInput.getId()).setText(detectLanguageInput.getText()) - .setCountryHint(detectLanguageInput.getCountryHint())).collect(Collectors.toList())); - - return service.languagesWithRestResponseAsync( - languageBatchInput, options == null ? null : options.getModelVersion(), - options == null ? null : options.showStatistics(), context) - .doOnSubscribe(ignoredValue -> logger.info("A batch of language input - {}", textInputs.toString())) - .doOnSuccess(response -> logger.info("A batch of detected language output - {}", response.getValue())) - .doOnError(error -> logger.warning("Failed to detected languages - {}", error)) - .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); - } - // Named Entity /** * Returns a list of general named entities in the provided text. For a list of supported entity types, check: @@ -327,21 +271,13 @@ public Mono recognizeEntities(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> recognizeEntitiesWithResponse(String text, String language) { try { - return withContext(context -> recognizeEntitiesWithResponse(text, language, context)); + return withContext(context -> + recognizeEntityAsyncClient.recognizeEntitiesWithResponse(text, language, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono> recognizeEntitiesWithResponse(String text, String language, - Context context) { - Objects.requireNonNull(text, "'text' cannot be null."); - - return recognizeBatchEntitiesWithResponse( - Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) - .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); - } - /** * Returns a list of general named entities for the provided list of texts. * @@ -377,21 +313,13 @@ public Mono> recognizeEntities public Mono>> recognizeEntitiesWithResponse( List textInputs, String language) { try { - return withContext(context -> recognizeEntitiesWithResponse(textInputs, language, context)); + return withContext(context -> recognizeEntityAsyncClient.recognizeEntitiesWithResponse(textInputs, language, + context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono>> recognizeEntitiesWithResponse( - List textInputs, String language, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - List documentInputs = mapByIndex(textInputs, (index, value) -> - new TextDocumentInput(index, value, language)); - return recognizeBatchEntitiesWithResponse(documentInputs, null, context); - } - /** * Returns a list of general named entities for the provided list of text inputs. * @@ -428,28 +356,13 @@ public Mono> recognizeBatchEnt public Mono>> recognizeBatchEntitiesWithResponse( List textInputs, TextAnalyticsRequestOptions options) { try { - return withContext(context -> recognizeBatchEntitiesWithResponse(textInputs, options, context)); + return withContext(context -> + recognizeEntityAsyncClient.recognizeBatchEntitiesWithResponse(textInputs, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono>> recognizeBatchEntitiesWithResponse( - List textInputs, TextAnalyticsRequestOptions options, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() - .setDocuments(convertToMultiLanguageInput(textInputs)); - return service.entitiesRecognitionGeneralWithRestResponseAsync( - batchInput, - options == null ? null : options.getModelVersion(), - options == null ? null : options.showStatistics(), context) - .doOnSubscribe(ignoredValue -> logger.info("A batch of named entities input - {}", textInputs.toString())) - .doOnSuccess(response -> logger.info("A batch of named entities output - {}", response.getValue())) - .doOnError(error -> logger.warning("Failed to named entities - {}", error)) - .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); - } - // PII Entity /** * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the text. For the list of @@ -488,21 +401,13 @@ public Mono recognizePiiEntities(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> recognizePiiEntitiesWithResponse(String text, String language) { try { - return withContext(context -> recognizePiiEntitiesWithResponse(text, language, context)); + return withContext(context -> recognizePiiEntityAsyncClient.recognizePiiEntitiesWithResponse(text, language, + context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono> recognizePiiEntitiesWithResponse(String text, String language, - Context context) { - Objects.requireNonNull(text, "'text' cannot be null."); - - return recognizeBatchPiiEntitiesWithResponse( - Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) - .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); - } - /** * Returns a list of personal information entities ("SSN", "Bank Account", etc) in the list of texts. For the list * of supported entity types, check: . For a list of enabled languages, @@ -543,20 +448,8 @@ public Mono> recognizePiiEn public Mono>> recognizePiiEntitiesWithResponse( List textInputs, String language) { try { - return withContext(context -> recognizePiiEntitiesWithResponse(textInputs, language, context)); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - Mono>> recognizePiiEntitiesWithResponse( - List textInputs, String language, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - List documentInputs = mapByIndex(textInputs, (index, value) -> - new TextDocumentInput(index, value, language)); - try { - return recognizeBatchPiiEntitiesWithResponse(documentInputs, null, context); + return withContext(context -> recognizePiiEntityAsyncClient.recognizePiiEntitiesWithResponse(textInputs, + language, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } @@ -602,27 +495,13 @@ public Mono> recognizeBatch public Mono>> recognizeBatchPiiEntitiesWithResponse( List textInputs, TextAnalyticsRequestOptions options) { try { - return withContext(context -> recognizeBatchPiiEntitiesWithResponse(textInputs, options, context)); + return withContext(context -> + recognizePiiEntityAsyncClient.recognizeBatchPiiEntitiesWithResponse(textInputs, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono>> recognizeBatchPiiEntitiesWithResponse( - List textInputs, TextAnalyticsRequestOptions options, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() - .setDocuments(convertToMultiLanguageInput(textInputs)); - return service.entitiesRecognitionPiiWithRestResponseAsync( - batchInput, - options == null ? null : options.getModelVersion(), - options == null ? null : options.showStatistics(), context) - .doOnSubscribe(ignoredValue -> logger.info("A batch of PII entities input - {}", textInputs.toString())) - .doOnSuccess(response -> logger.info("A batch of PII entities output - {}", response.getValue())) - .doOnError(error -> logger.warning("Failed to PII entities - {}", error)) - .map(response -> new SimpleResponse<>(response, toPiiDocumentResultCollection(response.getValue()))); - } - // Linked Entity /** * Returns a list of recognized entities with links to a well-known knowledge base for the provided text. See @@ -660,21 +539,13 @@ public Mono recognizeLinkedEntities(String text) public Mono> recognizeLinkedEntitiesWithResponse(String text, String language) { try { - return withContext(context -> recognizeLinkedEntitiesWithResponse(text, language, context)); + return withContext(context -> recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesWithResponse(text, + language, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono> recognizeLinkedEntitiesWithResponse(String text, String language, - Context context) { - Objects.requireNonNull(text, "'text' cannot be null."); - - return recognizeBatchLinkedEntitiesWithResponse( - Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) - .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); - } - /** * Returns a list of recognized entities with links to a well-known knowledge base for the list of texts. See * for supported languages in Text Analytics API. @@ -714,20 +585,8 @@ public Mono> recognizeLi public Mono>> recognizeLinkedEntitiesWithResponse( List textInputs, String language) { try { - return withContext(context -> recognizeLinkedEntitiesWithResponse(textInputs, language, context)); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - Mono>> recognizeLinkedEntitiesWithResponse( - List textInputs, String language, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - List documentInputs = mapByIndex(textInputs, (index, value) -> - new TextDocumentInput(index, value, language)); - try { - return recognizeBatchLinkedEntitiesWithResponse(documentInputs, null, context); + return withContext(context -> + recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesWithResponse(textInputs, language, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } @@ -772,29 +631,13 @@ public Mono> recognizeBa recognizeBatchLinkedEntitiesWithResponse(List textInputs, TextAnalyticsRequestOptions options) { try { - return withContext(context -> recognizeBatchLinkedEntitiesWithResponse(textInputs, options, context)); + return withContext(context -> recognizeLinkedEntityAsyncClient.recognizeBatchLinkedEntitiesWithResponse( + textInputs, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono>> recognizeBatchLinkedEntitiesWithResponse( - List textInputs, TextAnalyticsRequestOptions options, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() - .setDocuments(convertToMultiLanguageInput(textInputs)); - return service.entitiesLinkingWithRestResponseAsync( - batchInput, - options == null ? null : options.getModelVersion(), - options == null ? null : options.showStatistics(), context) - .doOnSubscribe(ignoredValue -> logger.info("A batch of linked entities input - {}", textInputs.toString())) - .doOnSuccess(response -> logger.info("A batch of linked entities output - {}", response.getValue())) - .doOnError(error -> logger.warning("Failed to linked entities - {}", error)) - .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); - } - - // Key Phrases /** * Returns a list of strings denoting the key phrases in the input text. @@ -830,21 +673,13 @@ public Mono extractKeyPhrases(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> extractKeyPhrasesWithResponse(String text, String language) { try { - return withContext(context -> extractKeyPhrasesWithResponse(text, language, context)); + return withContext(context -> extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(text, language, + context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono> extractKeyPhrasesWithResponse(String text, String language, - Context context) { - Objects.requireNonNull(text, "'text' cannot be null."); - - return extractBatchKeyPhrasesWithResponse( - Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) - .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); - } - /** * Returns a list of strings denoting the key phrases in the input text. * @@ -881,20 +716,8 @@ public Mono> extractKeyPhrases( public Mono>> extractKeyPhrasesWithResponse( List textInputs, String language) { try { - return withContext(context -> extractKeyPhrasesWithResponse(textInputs, language, context)); - } catch (RuntimeException ex) { - return monoError(logger, ex); - } - } - - Mono>> extractKeyPhrasesWithResponse( - List textInputs, String language, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - List documentInputs = mapByIndex(textInputs, (index, value) -> - new TextDocumentInput(index, value, language)); - try { - return extractBatchKeyPhrasesWithResponse(documentInputs, null, context); + return withContext(context -> extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(textInputs, + language, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } @@ -937,48 +760,13 @@ public Mono> extractBatchKeyPhr public Mono>> extractBatchKeyPhrasesWithResponse( List textInputs, TextAnalyticsRequestOptions options) { try { - return withContext(context -> extractBatchKeyPhrasesWithResponse(textInputs, options, context)); + return withContext(context -> + extractKeyPhraseAsyncClient.extractBatchKeyPhrasesWithResponse(textInputs, options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono>> extractBatchKeyPhrasesWithResponse( - List textInputs, TextAnalyticsRequestOptions options, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() - .setDocuments(convertToMultiLanguageInput(textInputs)); - return service.keyPhrasesWithRestResponseAsync( - batchInput, - options == null ? null : options.getModelVersion(), - options == null ? null : options.showStatistics(), context) - .doOnSubscribe(ignoredValue -> logger.info("A batch of key phrases input - {}", textInputs.toString())) - .doOnSuccess(response -> logger.info("A batch of key phrases output - {}", response.getValue())) - .doOnError(error -> logger.warning("Failed to key phrases - {}", error)) - .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); - } - - private DocumentResultCollection toDocumentResultCollection( - final com.azure.ai.textanalytics.implementation.models.KeyPhraseResult keyPhraseResult) { - List keyPhraseResultList = new ArrayList<>(); - for (DocumentKeyPhrases documentKeyPhrases : keyPhraseResult.getDocuments()) { - keyPhraseResultList.add(new ExtractKeyPhraseResult(documentKeyPhrases.getId(), - documentKeyPhrases.getStatistics() == null ? null - : convertToTextDocumentStatistics(documentKeyPhrases.getStatistics()), null, - documentKeyPhrases.getKeyPhrases())); - } - - for (DocumentError documentError : keyPhraseResult.getErrors()) { - final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); - keyPhraseResultList.add(new ExtractKeyPhraseResult(documentError.getId(), null, error, null)); - } - - return new DocumentResultCollection<>(keyPhraseResultList, - keyPhraseResult.getModelVersion(), keyPhraseResult.getStatistics() == null ? null - : mapBatchStatistics(keyPhraseResult.getStatistics())); - } - // Sentiment /** * Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and @@ -1015,20 +803,13 @@ public Mono analyzeSentiment(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Mono> analyzeSentimentWithResponse(String text, String language) { try { - return withContext(context -> analyzeSentimentWithResponse(text, language, context)); + return withContext(context -> + analyzeSentimentAsyncClient.analyzeSentimentWithResponse(text, language, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono> analyzeSentimentWithResponse(String text, String language, Context context) { - Objects.requireNonNull(text, "'text' cannot be null."); - - return analyzeBatchSentimentWithResponse( - Collections.singletonList(new TextDocumentInput("0", text, language)), null, context) - .map(response -> new SimpleResponse<>(response, response.getValue().iterator().next())); - } - /** * Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and * Neutral) for the document and each sentence within it. @@ -1066,21 +847,13 @@ public Mono> analyzeSentiment(L public Mono>> analyzeSentimentWithResponse( List textInputs, String language) { try { - return withContext(context -> analyzeSentimentWithResponse(textInputs, language, context)); + return withContext(context -> analyzeSentimentAsyncClient.analyzeSentimentWithResponse(textInputs, language, + context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - Mono>> analyzeSentimentWithResponse( - List textInputs, String language, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - List documentInputs = mapByIndex(textInputs, (index, value) -> - new TextDocumentInput(index, value, language)); - return analyzeBatchSentimentWithResponse(documentInputs, null, context); - } - /** * Returns a sentiment prediction, as well as sentiment scores for each sentiment class (Positive, Negative, and * Neutral) for the document and each sentence within it. @@ -1119,267 +892,10 @@ public Mono> analyzeBatchSentim public Mono>> analyzeBatchSentimentWithResponse( List textInputs, TextAnalyticsRequestOptions options) { try { - return withContext(context -> analyzeBatchSentimentWithResponse(textInputs, options, context)); + return withContext(context -> analyzeSentimentAsyncClient.analyzeBatchSentimentWithResponse(textInputs, + options, context)); } catch (RuntimeException ex) { return monoError(logger, ex); } } - - Mono>> analyzeBatchSentimentWithResponse( - List textInputs, TextAnalyticsRequestOptions options, Context context) { - Objects.requireNonNull(textInputs, "'textInputs' cannot be null."); - - final MultiLanguageBatchInput batchInput = new MultiLanguageBatchInput() - .setDocuments(convertToMultiLanguageInput(textInputs)); - return service.sentimentWithRestResponseAsync( - batchInput, - options == null ? null : options.getModelVersion(), - options == null ? null : options.showStatistics(), context) - .doOnSubscribe(ignoredValue -> logger.info("A batch of text sentiment input - {}", textInputs.toString())) - .doOnSuccess(response -> logger.info("A batch of text sentiment output - {}", response)) - .doOnError(error -> logger.warning("Failed to text sentiment - {}", error)) - .map(response -> new SimpleResponse<>(response, toDocumentResultCollection(response.getValue()))); - } - - private List convertToMultiLanguageInput(List textInputs) { - List multiLanguageInputs = new ArrayList<>(); - for (TextDocumentInput textDocumentInput : textInputs) { - multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) - .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); - } - return multiLanguageInputs; - } - - /** - * Helper method to convert the service response of {@link SentimentResponse} to {@link DocumentResultCollection}. - * - * @param sentimentResponse the {@link SentimentResponse} returned by the service. - * - * @return the {@link DocumentResultCollection} of {@link AnalyzeSentimentResult} to be returned by the SDK. - */ - private DocumentResultCollection toDocumentResultCollection( - final SentimentResponse sentimentResponse) { - List analyzeSentimentResults = new ArrayList<>(); - for (DocumentSentiment documentSentiment : sentimentResponse.getDocuments()) { - analyzeSentimentResults.add(convertToTextSentimentResult(documentSentiment)); - } - for (DocumentError documentError : sentimentResponse.getErrors()) { - final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); - analyzeSentimentResults.add(new AnalyzeSentimentResult(documentError.getId(), null, error, null, - null)); - } - return new DocumentResultCollection<>(analyzeSentimentResults, - sentimentResponse.getModelVersion(), sentimentResponse.getStatistics() == null ? null - : mapBatchStatistics(sentimentResponse.getStatistics())); - } - - private AnalyzeSentimentResult convertToTextSentimentResult(final DocumentSentiment documentSentiment) { - // Document text sentiment - final TextSentimentClass documentSentimentClass = TextSentimentClass.fromString(documentSentiment. - getSentiment().toString()); - if (documentSentimentClass == null) { - // Not throw exception for an invalid Sentiment type because we should not skip processing the - // other response. It is a service issue. - logger.logExceptionAsWarning( - new RuntimeException(String.format("'%s' is not valid text sentiment.", - documentSentiment.getSentiment()))); - } - final SentimentConfidenceScorePerLabel confidenceScorePerLabel = documentSentiment.getDocumentScores(); - - // Sentence text sentiment - final List sentenceSentimentTexts = documentSentiment.getSentences().stream() - .map(sentenceSentiment -> { - TextSentimentClass sentimentClass = TextSentimentClass.fromString(sentenceSentiment - .getSentiment().toString()); - if (sentimentClass == null) { - // Not throw exception for an invalid Sentiment type because we should not skip processing the - // other response. It is a service issue. - logger.logExceptionAsWarning( - new RuntimeException(String.format("'%s' is not valid text sentiment.", - sentenceSentiment.getSentiment()))); - } - SentimentConfidenceScorePerLabel confidenceScorePerSentence = sentenceSentiment.getSentenceScores(); - - return new TextSentiment(sentimentClass, confidenceScorePerSentence.getNegative(), - confidenceScorePerSentence.getNeutral(), confidenceScorePerSentence.getPositive(), - sentenceSentiment.getLength(), sentenceSentiment.getOffset()); - - }).collect(Collectors.toList()); - - return new AnalyzeSentimentResult(documentSentiment.getId(), - documentSentiment.getStatistics() == null ? null - : convertToTextDocumentStatistics(documentSentiment.getStatistics()), null, - new TextSentiment(documentSentimentClass, confidenceScorePerLabel.getNegative(), - confidenceScorePerLabel.getNeutral(), confidenceScorePerLabel.getPositive(), - sentenceSentimentTexts.stream().mapToInt(TextSentiment::getLength).sum(), 0), - sentenceSentimentTexts); - } - - /** - * Helper method to convert the service response of {@link LanguageResult} to {@link DocumentResultCollection}. - * - * @param languageResult the {@link LanguageResult} returned by the service. - * - * @return the {@link DocumentResultCollection} of {@link DetectLanguageResult} to be returned by the SDK. - */ - private DocumentResultCollection toDocumentResultCollection( - final LanguageResult languageResult) { - - final List detectLanguageResults = new ArrayList<>(); - for (DocumentLanguage documentLanguage : languageResult.getDocuments()) { - DetectedLanguage primaryLanguage = null; - if (documentLanguage.getDetectedLanguages().size() >= 1) { - com.azure.ai.textanalytics.implementation.models.DetectedLanguage detectedLanguageResult = - documentLanguage.getDetectedLanguages().get(0); - primaryLanguage = new DetectedLanguage(detectedLanguageResult.getName(), - detectedLanguageResult.getIso6391Name(), detectedLanguageResult.getScore()); - } - detectLanguageResults.add(new DetectLanguageResult(documentLanguage.getId(), - documentLanguage.getStatistics() == null - ? null : convertToTextDocumentStatistics(documentLanguage.getStatistics()), - null, - primaryLanguage, - documentLanguage.getDetectedLanguages().stream().map(detectedLanguage -> - new DetectedLanguage(detectedLanguage.getName(), detectedLanguage.getIso6391Name(), - detectedLanguage.getScore())).collect(Collectors.toList()))); - } - - for (DocumentError documentError : languageResult.getErrors()) { - com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); - detectLanguageResults.add( - new DetectLanguageResult(documentError.getId(), null, error, null, null)); - } - - return new DocumentResultCollection<>(detectLanguageResults, languageResult.getModelVersion(), - languageResult.getStatistics() == null ? null : mapBatchStatistics(languageResult.getStatistics())); - } - - /** - * Helper method to convert the service response of {@link EntitiesResult} to {@link DocumentResultCollection}. - * - * @param entitiesResult the {@link EntitiesResult} returned by the service. - * - * @return the {@link DocumentResultCollection} of {@link DetectLanguageResult} to be returned by the SDK. - */ - private DocumentResultCollection toDocumentResultCollection( - final EntitiesResult entitiesResult) { - List recognizeEntitiesResults = new ArrayList<>(); - for (DocumentEntities documentEntities : entitiesResult.getDocuments()) { - recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentEntities.getId(), - documentEntities.getStatistics() == null ? null - : convertToTextDocumentStatistics(documentEntities.getStatistics()), - null, documentEntities.getEntities().stream().map(entity -> - new NamedEntity(entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), - entity.getLength(), entity.getScore())).collect(Collectors.toList()))); - } - - for (DocumentError documentError : entitiesResult.getErrors()) { - final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); - recognizeEntitiesResults.add(new RecognizeEntitiesResult(documentError.getId(), null, error, null)); - } - - return new DocumentResultCollection<>(recognizeEntitiesResults, - entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null - : mapBatchStatistics(entitiesResult.getStatistics())); - } - - /** - * Helper method to convert the service response of {@link EntitiesResult} to {@link DocumentResultCollection}. - * - * @param entitiesResult the {@link EntitiesResult} returned by the service. - * - * @return the {@link DocumentResultCollection} of {@link RecognizePiiEntitiesResult} to be returned by the SDK. - */ - private DocumentResultCollection toPiiDocumentResultCollection( - final EntitiesResult entitiesResult) { - List recognizePiiEntitiesResults = new ArrayList<>(); - for (DocumentEntities documentEntities : entitiesResult.getDocuments()) { - recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(documentEntities.getId(), - documentEntities.getStatistics() == null ? null - : convertToTextDocumentStatistics(documentEntities.getStatistics()), - null, documentEntities.getEntities().stream().map(entity -> - new NamedEntity(entity.getText(), entity.getType(), entity.getSubtype(), entity.getOffset(), - entity.getLength(), entity.getScore())).collect(Collectors.toList()))); - } - - for (DocumentError documentError : entitiesResult.getErrors()) { - final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); - recognizePiiEntitiesResults.add(new RecognizePiiEntitiesResult(documentError.getId(), null, error, null)); - } - - return new DocumentResultCollection<>(recognizePiiEntitiesResults, - entitiesResult.getModelVersion(), entitiesResult.getStatistics() == null ? null - : mapBatchStatistics(entitiesResult.getStatistics())); - } - - /** - * Helper method to convert the service response of {@link EntityLinkingResult} to {@link DocumentResultCollection}. - * - * @param entityLinkingResult the {@link EntityLinkingResult} returned by the service. - * - * @return the {@link DocumentResultCollection} of {@link RecognizeLinkedEntitiesResult} to be returned by the SDK. - */ - private DocumentResultCollection toDocumentResultCollection( - final EntityLinkingResult entityLinkingResult) { - List linkedEntitiesResults = new ArrayList<>(); - for (DocumentLinkedEntities documentLinkedEntities : entityLinkingResult.getDocuments()) { - linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentLinkedEntities.getId(), - documentLinkedEntities.getStatistics() == null ? null - : convertToTextDocumentStatistics(documentLinkedEntities.getStatistics()), - null, mapLinkedEntity(documentLinkedEntities.getEntities()))); - } - for (DocumentError documentError : entityLinkingResult.getErrors()) { - final com.azure.ai.textanalytics.models.TextAnalyticsError error = convertToError(documentError.getError()); - linkedEntitiesResults.add(new RecognizeLinkedEntitiesResult(documentError.getId(), null, error, null)); - } - - return new DocumentResultCollection<>(linkedEntitiesResults, - entityLinkingResult.getModelVersion(), entityLinkingResult.getStatistics() == null ? null - : mapBatchStatistics(entityLinkingResult.getStatistics())); - } - - private static List mapByIndex(List textInputs, BiFunction mappingFunction) { - return IntStream.range(0, textInputs.size()) - .mapToObj(index -> mappingFunction.apply(String.valueOf(index), textInputs.get(index))) - .collect(Collectors.toList()); - } - - private TextDocumentStatistics convertToTextDocumentStatistics(DocumentStatistics statistics) { - return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); - } - - private TextDocumentBatchStatistics mapBatchStatistics(RequestStatistics statistics) { - return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getErroneousDocumentsCount(), - statistics.getValidDocumentsCount(), statistics.getTransactionsCount()); - } - - private List mapLinkedEntity(List linkedEntities) { - List linkedEntitiesList = new ArrayList<>(); - for (LinkedEntity linkedEntity : linkedEntities) { - linkedEntitiesList.add(new com.azure.ai.textanalytics.models.LinkedEntity(linkedEntity.getName(), - linkedEntity.getMatches().stream().map(match -> - new LinkedEntityMatch(match.getText(), match.getScore(), match.getLength(), - match.getOffset())).collect(Collectors.toList()), linkedEntity.getLanguage(), - linkedEntity.getId(), linkedEntity.getUrl(), linkedEntity.getDataSource())); - } - return linkedEntitiesList; - } - - private com.azure.ai.textanalytics.models.TextAnalyticsError convertToError(TextAnalyticsError textAnalyticsError) { - return new com.azure.ai.textanalytics.models.TextAnalyticsError( - ErrorCodeValue.fromString(textAnalyticsError.getCode().toString()), textAnalyticsError.getMessage(), - textAnalyticsError.getTarget(), textAnalyticsError.getDetails() == null ? null - : setErrors(textAnalyticsError.getDetails())); - } - - private List setErrors(List details) { - List detailsList = new ArrayList<>(); - for (TextAnalyticsError error : details) { - detailsList.add(new com.azure.ai.textanalytics.models.TextAnalyticsError( - ErrorCodeValue.fromString(error.getCode().toString()), - error.getMessage(), - error.getTarget(), error.getDetails() == null ? null : setErrors(error.getDetails()))); - } - return detailsList; - } } diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClient.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClient.java index a549176746e19..288d93f614896 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClient.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/TextAnalyticsClient.java @@ -3,16 +3,16 @@ package com.azure.ai.textanalytics; +import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; import com.azure.ai.textanalytics.models.DetectLanguageInput; import com.azure.ai.textanalytics.models.DetectLanguageResult; import com.azure.ai.textanalytics.models.DocumentResultCollection; import com.azure.ai.textanalytics.models.ExtractKeyPhraseResult; -import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; +import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; import com.azure.ai.textanalytics.models.RecognizePiiEntitiesResult; import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; import com.azure.ai.textanalytics.models.TextDocumentInput; -import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; import com.azure.core.annotation.ReturnType; import com.azure.core.annotation.ServiceClient; import com.azure.core.annotation.ServiceMethod; @@ -90,7 +90,7 @@ public DetectLanguageResult detectLanguage(String text, String countryHint) { */ @ServiceMethod(returns = ReturnType.SINGLE) public Response detectLanguageWithResponse(String text, String countryHint, Context context) { - return client.detectLanguageWithResponse(text, countryHint, context).block(); + return client.detectLanguageAsyncClient.detectLanguageWithResponse(text, countryHint, context).block(); } /** @@ -122,7 +122,7 @@ public DocumentResultCollection detectLanguages(List> detectLanguagesWithResponse( List textInputs, String countryHint, Context context) { - return client.detectLanguagesWithResponse(textInputs, countryHint, context).block(); + return client.detectLanguageAsyncClient.detectLanguagesWithResponse(textInputs, countryHint, context).block(); } /** @@ -153,11 +153,10 @@ public DocumentResultCollection detectBatchLanguages(List< @ServiceMethod(returns = ReturnType.SINGLE) public Response> detectBatchLanguagesWithResponse( List textInputs, TextAnalyticsRequestOptions options, Context context) { - return client.detectBatchLanguagesWithResponse(textInputs, options, context).block(); + return client.detectLanguageAsyncClient.detectBatchLanguagesWithResponse(textInputs, options, context).block(); } // Named Entity - /** * Returns a list of general named entities in the provided text. * For a list of supported entity types, check: @@ -187,7 +186,7 @@ public RecognizeEntitiesResult recognizeEntities(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Response recognizeEntitiesWithResponse( String text, String language, Context context) { - return client.recognizeEntitiesWithResponse(text, language, context).block(); + return client.recognizeEntityAsyncClient.recognizeEntitiesWithResponse(text, language, context).block(); } /** @@ -218,7 +217,7 @@ public DocumentResultCollection recognizeEntities(List< @ServiceMethod(returns = ReturnType.SINGLE) public Response> recognizeEntitiesWithResponse( List textInputs, String language, Context context) { - return client.recognizeEntitiesWithResponse(textInputs, language, context).block(); + return client.recognizeEntityAsyncClient.recognizeEntitiesWithResponse(textInputs, language, context).block(); } /** @@ -250,7 +249,8 @@ public DocumentResultCollection recognizeBatchEntities( @ServiceMethod(returns = ReturnType.SINGLE) public Response> recognizeBatchEntitiesWithResponse( List textInputs, TextAnalyticsRequestOptions options, Context context) { - return client.recognizeBatchEntitiesWithResponse(textInputs, options, context).block(); + return client.recognizeEntityAsyncClient.recognizeBatchEntitiesWithResponse(textInputs, options, + context).block(); } // PII Entities @@ -286,7 +286,7 @@ public RecognizePiiEntitiesResult recognizePiiEntities(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Response recognizePiiEntitiesWithResponse(String text, String language, Context context) { - return client.recognizePiiEntitiesWithResponse(text, language, context).block(); + return client.recognizePiiEntityAsyncClient.recognizePiiEntitiesWithResponse(text, language, context).block(); } /** @@ -322,7 +322,8 @@ public DocumentResultCollection recognizePiiEntities @ServiceMethod(returns = ReturnType.SINGLE) public Response> recognizePiiEntitiesWithResponse( List textInputs, String language, Context context) { - return client.recognizePiiEntitiesWithResponse(textInputs, language, context).block(); + return client.recognizePiiEntityAsyncClient.recognizePiiEntitiesWithResponse(textInputs, language, + context).block(); } /** @@ -358,7 +359,8 @@ public DocumentResultCollection recognizeBatchPiiEnt @ServiceMethod(returns = ReturnType.SINGLE) public Response> recognizeBatchPiiEntitiesWithResponse( List textInputs, TextAnalyticsRequestOptions options, Context context) { - return client.recognizeBatchPiiEntitiesWithResponse(textInputs, options, context).block(); + return client.recognizePiiEntityAsyncClient.recognizeBatchPiiEntitiesWithResponse(textInputs, options, + context).block(); } // Linked Entities @@ -392,7 +394,8 @@ public RecognizeLinkedEntitiesResult recognizeLinkedEntities(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Response recognizeLinkedEntitiesWithResponse(String text, String language, Context context) { - return client.recognizeLinkedEntitiesWithResponse(text, language, context).block(); + return client.recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesWithResponse(text, language, + context).block(); } /** @@ -426,7 +429,8 @@ public DocumentResultCollection recognizeLinkedEn @ServiceMethod(returns = ReturnType.SINGLE) public Response> recognizeLinkedEntitiesWithResponse( List textInputs, String language, Context context) { - return client.recognizeLinkedEntitiesWithResponse(textInputs, language, context).block(); + return client.recognizeLinkedEntityAsyncClient.recognizeLinkedEntitiesWithResponse(textInputs, language, + context).block(); } /** @@ -460,11 +464,11 @@ public DocumentResultCollection recognizeBatchLin @ServiceMethod(returns = ReturnType.SINGLE) public Response> recognizeBatchLinkedEntitiesWithResponse( List textInputs, TextAnalyticsRequestOptions options, Context context) { - return client.recognizeBatchLinkedEntitiesWithResponse(textInputs, options, context).block(); + return client.recognizeLinkedEntityAsyncClient.recognizeBatchLinkedEntitiesWithResponse(textInputs, options, + context).block(); } // Key Phrase - /** * Returns a list of strings denoting the key phrases in the input text. * @@ -494,7 +498,7 @@ public ExtractKeyPhraseResult extractKeyPhrases(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Response extractKeyPhrasesWithResponse(String text, String language, Context context) { - return client.extractKeyPhrasesWithResponse(text, language, context).block(); + return client.extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(text, language, context).block(); } /** @@ -526,7 +530,7 @@ public DocumentResultCollection extractKeyPhrases(List> extractKeyPhrasesWithResponse( List textInputs, String language, Context context) { - return client.extractKeyPhrasesWithResponse(textInputs, language, context).block(); + return client.extractKeyPhraseAsyncClient.extractKeyPhrasesWithResponse(textInputs, language, context).block(); } /** @@ -558,7 +562,8 @@ public DocumentResultCollection extractBatchKeyPhrases(L @ServiceMethod(returns = ReturnType.SINGLE) public Response> extractBatchKeyPhrasesWithResponse( List textInputs, TextAnalyticsRequestOptions options, Context context) { - return client.extractBatchKeyPhrasesWithResponse(textInputs, options, context).block(); + return client.extractKeyPhraseAsyncClient.extractBatchKeyPhrasesWithResponse(textInputs, options, + context).block(); } // Sentiment @@ -591,7 +596,7 @@ public AnalyzeSentimentResult analyzeSentiment(String text) { @ServiceMethod(returns = ReturnType.SINGLE) public Response analyzeBatchSentimentWithResponse( String text, String language, Context context) { - return client.analyzeSentimentWithResponse(text, language, context).block(); + return client.analyzeSentimentAsyncClient.analyzeSentimentWithResponse(text, language, context).block(); } /** @@ -625,7 +630,7 @@ public DocumentResultCollection analyzeSentiment(List> analyzeSentimentWithResponse( List textInputs, String language, Context context) { - return client.analyzeSentimentWithResponse(textInputs, language, context).block(); + return client.analyzeSentimentAsyncClient.analyzeSentimentWithResponse(textInputs, language, context).block(); } /** @@ -658,6 +663,7 @@ public DocumentResultCollection analyzeBatchSentiment(Li @ServiceMethod(returns = ReturnType.SINGLE) public Response> analyzeBatchSentimentWithResponse( List textInputs, TextAnalyticsRequestOptions options, Context context) { - return client.analyzeBatchSentimentWithResponse(textInputs, options, context).block(); + return client.analyzeSentimentAsyncClient.analyzeBatchSentimentWithResponse(textInputs, options, + context).block(); } } diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/Transforms.java b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/Transforms.java new file mode 100644 index 0000000000000..bb87131a9018f --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/main/java/com/azure/ai/textanalytics/Transforms.java @@ -0,0 +1,107 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.implementation.models.DocumentStatistics; +import com.azure.ai.textanalytics.implementation.models.MultiLanguageInput; +import com.azure.ai.textanalytics.implementation.models.RequestStatistics; +import com.azure.ai.textanalytics.implementation.models.TextAnalyticsError; +import com.azure.ai.textanalytics.models.ErrorCodeValue; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.ai.textanalytics.models.TextDocumentStatistics; + +import java.util.ArrayList; +import java.util.List; +import java.util.function.BiFunction; +import java.util.stream.Collectors; +import java.util.stream.IntStream; + +/** + * Helper class to convert service level models to SDK exposes models. + */ +class Transforms { + + /** + * Given a list of inputs will apply the indexing function to it and return the updated list. + * + * @param textInputs the inputs to apply the mapping function to. + * @param mappingFunction the function which applies the index to the incoming input value. + * @param the type of items being returned in the list. + * @return The list holding all the generic items combined. + */ + static List mapByIndex(List textInputs, BiFunction mappingFunction) { + return IntStream.range(0, textInputs.size()) + .mapToObj(index -> mappingFunction.apply(String.valueOf(index), textInputs.get(index))) + .collect(Collectors.toList()); + } + + /** + * Convert {@link DocumentStatistics} to {@link TextDocumentStatistics} + * + * @param statistics the {@link DocumentStatistics} provided by the service. + * @return the {@link TextDocumentStatistics} returned by the SDK. + */ + static TextDocumentStatistics toTextDocumentStatistics(DocumentStatistics statistics) { + return new TextDocumentStatistics(statistics.getCharactersCount(), statistics.getTransactionsCount()); + } + + /** + * Convert {@link RequestStatistics} to {@link TextDocumentBatchStatistics} + * + * @param statistics the {@link RequestStatistics} provided by the service. + * @return the {@link TextDocumentBatchStatistics} returned by the SDK. + */ + static TextDocumentBatchStatistics toBatchStatistics(RequestStatistics statistics) { + return new TextDocumentBatchStatistics(statistics.getDocumentsCount(), statistics.getValidDocumentsCount(), + statistics.getErroneousDocumentsCount(), statistics.getTransactionsCount()); + } + + /** + * Convert {@link TextAnalyticsError} to {@link com.azure.ai.textanalytics.models.TextAnalyticsError} + * + * @param textAnalyticsError the {@link TextAnalyticsError} returned by the service. + * @return the {@link com.azure.ai.textanalytics.models.TextAnalyticsError} returned by the SDK. + */ + static com.azure.ai.textanalytics.models.TextAnalyticsError toTextAnalyticsError( + TextAnalyticsError textAnalyticsError) { + return new com.azure.ai.textanalytics.models.TextAnalyticsError( + ErrorCodeValue.fromString(textAnalyticsError.getCode().toString()), textAnalyticsError.getMessage(), + textAnalyticsError.getTarget(), textAnalyticsError.getDetails() == null ? null + : setErrors(textAnalyticsError.getDetails())); + } + + /** + * Convert the incoming input {@link TextDocumentInput} to the service expected {@link MultiLanguageInput}. + * + * @param textInputs the user provided input in {@link TextDocumentInput} + * @return the service required input {@link MultiLanguageInput} + */ + static List toMultiLanguageInput(List textInputs) { + List multiLanguageInputs = new ArrayList<>(); + for (TextDocumentInput textDocumentInput : textInputs) { + multiLanguageInputs.add(new MultiLanguageInput().setId(textDocumentInput.getId()) + .setText(textDocumentInput.getText()).setLanguage(textDocumentInput.getLanguage())); + } + return multiLanguageInputs; + } + + /** + * Helper method to set error details on {@link TextAnalyticsError}. + * + * @param details about specific errors that led to this reported error. + * @return the {@link TextAnalyticsError} returned by the SDK. + */ + private static List setErrors( + List details) { + List detailsList = new ArrayList<>(); + for (TextAnalyticsError error : details) { + detailsList.add(new com.azure.ai.textanalytics.models.TextAnalyticsError( + ErrorCodeValue.fromString(error.getCode().toString()), + error.getMessage(), + error.getTarget(), error.getDetails() == null ? null : setErrors(error.getDetails()))); + } + return detailsList; + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md b/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md index 66f00a95a29cf..e0a37e74a2b40 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/README.md @@ -22,6 +22,7 @@ The following sections provide several code snippets covering some of the most c - [Recognize linked entities in text][sample_linked_entities] - [Extract key phrases in text][sample_key_phrases] - [Analyze sentiment in text.][sample_sentiment] +- [Async Detect language in text][async_sample_hello_world] Batch Samples: - [Detect language for a batch of documents][sample_language_batch] @@ -50,18 +51,19 @@ Guidelines](../../CONTRIBUTING.md) for more information. [SDK_README_DEPENDENCY]: ../../README.md#adding-the-package-to-your-product [SDK_README_NEXT_STEPS]: ../../README.md#next-steps -[sample_hello_world]: java/com/azure/cs/textanalytics/HelloWorld.java -[sample_entities]: java/com/azure/cs/textanalytics/RecognizeEntities.java -[sample_pii_entities]: java/com/azure/cs/textanalytics/RecognizePII.java -[sample_linked_entities]: java/com/azure/cs/textanalytics/RecognizeLinkedEntities.java -[sample_key_phrases]: java/com/azure/cs/textanalytics/RecognizeKeyPhrases.java -[sample_sentiment]: java/com/azure/cs/textanalytics/DetectSentiment.java +[async_sample_hello_world]: java/com/azure/ai/textanalytics/DetectLanguageAsync.java +[sample_hello_world]: java/com/azure/ai/textanalytics/DetectLanguage.java +[sample_entities]: java/com/azure/ai/textanalytics/RecognizeEntities.java +[sample_pii_entities]: java/com/azure/ai/textanalytics/RecognizePii.java +[sample_linked_entities]: java/com/azure/ai/textanalytics/RecognizeLinkedEntities.java +[sample_key_phrases]: java/com/azure/ai/textanalytics/ExtractKeyPhrases.java +[sample_sentiment]: java/com/azure/ai/textanalytics/AnalyzeSentiment.java -[sample_language_batch]: java/com/azure/cs/textanalytics/batch/DetectLanguageBatchDocuments.java -[sample_entities_batch]: java/com/azure/cs/textanalytics/batch/RecognizeEntitiesBatchDocuments.java -[sample_pii_entities_batch]: java/com/azure/cs/textanalytics/batch/RecognizePiiBatchDocuments.java -[sample_linked_entities_batch]: java/com/azure/cs/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java -[sample_key_phrases_batch]: java/com/azure/cs/textanalytics/batch/RecognizeKeyPhrasesBatchDocuments.java -[sample_sentiment_batch]: java/com/azure/cs/textanalytics/batch/DetectSentimentBatchDocuments.java +[sample_language_batch]: java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocuments.java +[sample_entities_batch]: java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocuments.java +[sample_pii_entities_batch]: java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocuments.java +[sample_linked_entities_batch]: java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java +[sample_key_phrases_batch]: java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocuments.java +[sample_sentiment_batch]: java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocuments.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/src/samples/java/com/azure/ai/textanalytics/AnalyzeSentiment.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/AnalyzeSentiment.java index 7273908ac2854..33c55e930677c 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/AnalyzeSentiment.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/AnalyzeSentiment.java @@ -6,22 +6,20 @@ import com.azure.ai.textanalytics.models.TextSentiment; import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; -import java.util.List; - /** - * Sample demonstrate how to analyze sentiment of a text input. + * Sample demonstrates how to analyze the sentiment of an input text. */ public class AnalyzeSentiment { /** - * Main method to invoke this demo about how to analyze sentiment of a text input. + * Main method to invoke this demo about how to analyze the sentiment of an input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The text that need be analysed. @@ -31,16 +29,15 @@ public static void main(String[] args) { final TextSentiment documentSentiment = sentimentResult.getDocumentSentiment(); System.out.printf( - "Recognized TextSentiment: %s, Positive Score: %s, Neutral Score: %s, Negative Score: %s.%n", + "Recognized sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n", documentSentiment.getTextSentimentClass(), documentSentiment.getPositiveScore(), documentSentiment.getNeutralScore(), documentSentiment.getNegativeScore()); - final List sentiments = sentimentResult.getSentenceSentiments(); - for (TextSentiment textSentiment : sentiments) { + for (TextSentiment textSentiment : sentimentResult.getSentenceSentiments()) { System.out.printf( - "Recognized Sentence TextSentiment: %s, Positive Score: %s, Neutral Score: %s, Negative Score: %s.%n", + "Recognized sentence sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n", textSentiment.getTextSentimentClass(), textSentiment.getPositiveScore(), textSentiment.getNeutralScore(), diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/AnalyzeSentimentAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/AnalyzeSentimentAsync.java new file mode 100644 index 0000000000000..66339c3867bd4 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/AnalyzeSentimentAsync.java @@ -0,0 +1,59 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.TextSentiment; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously analyze the sentiment of an input text. + * */ +public class AnalyzeSentimentAsync { + /** + * Main method to invoke this demo about how to analyze the sentiment of an input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The text that need be analysed. + String text = "The hotel was dark and unclean."; + + client.analyzeSentiment(text).subscribe( + result -> { + final TextSentiment documentSentiment = result.getDocumentSentiment(); + System.out.printf( + "Recognized sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n", + documentSentiment.getTextSentimentClass(), + documentSentiment.getPositiveScore(), + documentSentiment.getNeutralScore(), + documentSentiment.getNegativeScore()); + + for (TextSentiment textSentiment : result.getSentenceSentiments()) { + System.out.printf( + "Recognized sentence sentiment: %s, positive score: %s, neutral score: %s, negative score: %s.%n", + textSentiment.getTextSentimentClass(), + textSentiment.getPositiveScore(), + textSentiment.getNeutralScore(), + textSentiment.getNegativeScore()); + } + }, + error -> System.err.println("There was an error analyzing sentiment of the text." + error), + () -> System.out.println("Sentiment analyzed.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/DetectLanguage.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/DetectLanguage.java new file mode 100644 index 0000000000000..32eddc8f19e0d --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/DetectLanguage.java @@ -0,0 +1,42 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DetectedLanguage; + +/** + * Sample demonstrates how to detect the language of an input text. + */ +public class DetectLanguage { + /** + * Main method to invoke this demo about how to detect the language of an input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildClient(); + + // The text that need be analysed. + String text = "hello world"; + + final DetectLanguageResult detectLanguageResult = client.detectLanguage(text, "US"); + final DetectedLanguage detectedPrimaryLanguage = detectLanguageResult.getPrimaryLanguage(); + System.out.printf("Detected primary language: %s, ISO 6391 name: %s, score: %s.%n", + detectedPrimaryLanguage.getName(), + detectedPrimaryLanguage.getIso6391Name(), + detectedPrimaryLanguage.getScore()); + + for (DetectedLanguage detectedLanguage : detectLanguageResult.getDetectedLanguages()) { + System.out.printf("Another detected language: %s, ISO 6391 name: %s, score: %s.%n", + detectedLanguage.getName(), + detectedLanguage.getIso6391Name(), + detectedLanguage.getScore()); + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/DetectLanguageAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/DetectLanguageAsync.java new file mode 100644 index 0000000000000..a1dc376928d13 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/DetectLanguageAsync.java @@ -0,0 +1,52 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.DetectedLanguage; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously detect the language of an input text. + */ +public class DetectLanguageAsync { + /** + * Main method to invoke this demo about how to detect the language of an input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The text that need be analysed. + String text = "hello world"; + + client.detectLanguage(text).subscribe( + result -> { + final DetectedLanguage primaryLanguage = result.getPrimaryLanguage(); + System.out.printf("Detected primary language: %s, ISO 6391 name: %s, score: %s.%n", + primaryLanguage.getName(), primaryLanguage.getIso6391Name(), primaryLanguage.getScore()); + for (DetectedLanguage detectedLanguage : result.getDetectedLanguages()) { + System.out.printf("Another detected language: %s, ISO 6391 name: %s, score: %s.%n", + detectedLanguage.getName(), + detectedLanguage.getIso6391Name(), + detectedLanguage.getScore()); + } + }, + error -> System.err.println("There was an error detecting language of the text." + error), + () -> System.out.println("Language detected.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrases.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrases.java index 73c1d6cfcf8e3..23d752ac72eee 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrases.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrases.java @@ -4,26 +4,26 @@ package com.azure.ai.textanalytics; /** - * Sample demonstrate how to analyze key phrases of a text input. + * Sample demonstrates how to extract the key phrases of an input text. */ public class ExtractKeyPhrases { /** - * Main method to invoke this demo about how to extract key phrases of a text input. + * Main method to invoke this demo about how to extract the key phrases of an input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The text that need be analysed. String text = "My cat might need to see a veterinarian."; for (String keyPhrase : client.extractKeyPhrases(text).getKeyPhrases()) { - System.out.printf("Recognized Phrases: %s.%n", keyPhrase); + System.out.printf("Recognized phrases: %s.%n", keyPhrase); } } } diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrasesAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrasesAsync.java new file mode 100644 index 0000000000000..8049c2bf4c6c5 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ExtractKeyPhrasesAsync.java @@ -0,0 +1,44 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously extract the key phrases of an input text. + */ +public class ExtractKeyPhrasesAsync { + /** + * Main method to invoke this demo about how to extract the key phrases of an input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The text that need be analysed. + String text = "My cat might need to see a veterinarian."; + + client.extractKeyPhrases(text).subscribe( + result -> { + for (String keyPhrase : result.getKeyPhrases()) { + System.out.printf("Recognized phrases: %s.%n", keyPhrase); + } + }, + error -> System.err.println("There was an error extracting key phrases of the text." + error), + () -> System.out.println("Key phrases extracted.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ReadmeSamples.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ReadmeSamples.java new file mode 100644 index 0000000000000..d78116526e290 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/ReadmeSamples.java @@ -0,0 +1,164 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.DetectedLanguage; +import com.azure.ai.textanalytics.models.LinkedEntity; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.TextSentiment; +import com.azure.core.http.HttpClient; +import com.azure.core.http.netty.NettyAsyncHttpClientBuilder; +import com.azure.identity.DefaultAzureCredentialBuilder; + +/** + * 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. + * + * Class containing code snippets that will be injected to README.md. + */ +public class ReadmeSamples { + private static final String SUBSCRIPTION_KEY = null; + private static final String ENDPOINT = null; + + /** + * Code snippet for getting sync client using subscription key authentication. + */ + public void useSubscriptionKeySyncClient() { + TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildClient(); + } + + /** + * Code snippet for getting async client using subscription key authentication. + */ + public void useSubscriptionKeyAsyncClient() { + TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildAsyncClient(); + } + + /** + * Code snippet for getting async client using AAD authentication. + */ + public void useAadAsyncClient() { + TextAnalyticsAsyncClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .endpoint(ENDPOINT) + .credential(new DefaultAzureCredentialBuilder().build()) + .buildAsyncClient(); + } + + /** + * Code snippet for detecting language in a text. + */ + public void detectLanguages() { + TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildClient(); + + String inputText = "Bonjour tout le monde"; + + for (DetectedLanguage detectedLanguage : textAnalyticsClient.detectLanguage(inputText).getDetectedLanguages()) { + System.out.printf("Detected languages name: %s, ISO 6391 Name: %s, Score: %s.%n", + detectedLanguage.getName(), + detectedLanguage.getIso6391Name(), + detectedLanguage.getScore()); + } + } + + /** + * Code snippet for recognizing named entity in a text. + */ + public void recognizeNamedEntity() { + TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildClient(); + + String text = "Satya Nadella is the CEO of Microsoft"; + + for (NamedEntity entity : textAnalyticsClient.recognizeEntities(text).getNamedEntities()) { + System.out.printf( + "Recognized Named Entity: %s, Type: %s, Subtype: %s, Score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype(), + entity.getScore()); + } + } + + /** + * Code snippet for recognizing pii entity in a text. + */ + public void recognizePiiEntity() { + TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildClient(); + + // The text that need be analysed. + String text = "My SSN is 555-55-5555"; + + for (NamedEntity entity : textAnalyticsClient.recognizePiiEntities(text).getNamedEntities()) { + System.out.printf( + "Recognized PII Entity: %s, Type: %s, Subtype: %s, Score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype(), + entity.getScore()); + } + } + + /** + * Code snippet for recognizing linked entity in a text. + */ + public void recognizeLinkedEntity() { + TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildClient(); + + // The text that need be analysed. + String text = "Old Faithful is a geyser at Yellowstone Park."; + + for (LinkedEntity linkedEntity : textAnalyticsClient.recognizeLinkedEntities(text).getLinkedEntities()) { + System.out.printf("Recognized Linked Entity: %s, Url: %s, Data Source: %s.%n", + linkedEntity.getName(), + linkedEntity.getUrl(), + linkedEntity.getDataSource()); + } + } + + /** + * Code snippet for analyzing sentiment of a text. + */ + public void analyzeSentiment() { + TextAnalyticsClient textAnalyticsClient = new TextAnalyticsClientBuilder() + .subscriptionKey(SUBSCRIPTION_KEY) + .endpoint(ENDPOINT) + .buildClient(); + + String text = "The hotel was dark and unclean."; + + for (TextSentiment textSentiment : textAnalyticsClient.analyzeSentiment(text).getSentenceSentiments()) { + System.out.printf( + "Analyzed Sentence Sentiment class: %s.%n", + textSentiment.getTextSentimentClass()); + } + } + + /** + * Code snippet for configuring http client. + */ + public void configureHttpClient() { + HttpClient client = new NettyAsyncHttpClientBuilder() + .port(8080) + .wiretap(true) + .build(); + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntities.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntities.java index bda25d0026e04..f0d940a356805 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntities.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntities.java @@ -6,19 +6,19 @@ import com.azure.ai.textanalytics.models.NamedEntity; /** - * Sample demonstrate how to recognize entities of a text input. + * Sample demonstrates how to recognize the entities of an input text. */ public class RecognizeEntities { /** - * Main method to invoke this demo about how to recognize entities of a text input. + * Main method to invoke this demo about how to recognize the entities of an input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The text that need be analysed. @@ -26,10 +26,10 @@ public static void main(String[] args) { for (NamedEntity entity : client.recognizeEntities(text).getNamedEntities()) { System.out.printf( - "Recognized NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", + "Recognized entity: %s, entity type: %s, entity subtype: %s, offset: %s, length: %s, score: %s.%n", entity.getText(), entity.getType(), - entity.getSubtype(), + entity.getSubtype() == null || entity.getSubtype().isEmpty() ? "N/A" : entity.getSubtype(), entity.getOffset(), entity.getLength(), entity.getScore()); diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntitiesAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntitiesAsync.java new file mode 100644 index 0000000000000..9e831c43611ce --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeEntitiesAsync.java @@ -0,0 +1,53 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.NamedEntity; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously recognize the entities of an input text. + */ +public class RecognizeEntitiesAsync { + /** + * Main method to invoke this demo about how to recognize the entities of an input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The text that need be analysed. + String text = "Satya Nadella is the CEO of Microsoft"; + + client.recognizeEntities(text).subscribe( + result -> { + for (NamedEntity entity : result.getNamedEntities()) { + System.out.printf( + "Recognized entity: %s, entity type: %s, entity subtype: %s, offset: %s, length: %s, score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype() == null || entity.getSubtype().isEmpty() ? "N/A" : entity.getSubtype(), + entity.getOffset(), + entity.getLength(), + entity.getScore()); + } + }, + error -> System.err.println("There was an error recognizing entities of the text." + error), + () -> System.out.println("Entities recognized.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntities.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntities.java index 20f9f166638f0..9e01255b55aec 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntities.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntities.java @@ -6,26 +6,26 @@ import com.azure.ai.textanalytics.models.LinkedEntity; /** - * Sample demonstrate how to recognize linked entities of a text input. + * Sample demonstrates how to recognize the linked entities of an input text. */ public class RecognizeLinkedEntities { /** - * Main method to invoke this demo about how to recognize linked entities of a text input. + * Main method to invoke this demo about how to recognize the linked entities of an input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The text that need be analysed. String text = "Old Faithful is a geyser at Yellowstone Park."; for (LinkedEntity linkedEntity : client.recognizeLinkedEntities(text).getLinkedEntities()) { - System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s.%n", + System.out.printf("Recognized linked entity: %s, URL: %s, data source: %s.%n", linkedEntity.getName(), linkedEntity.getUrl(), linkedEntity.getDataSource()); diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntitiesAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntitiesAsync.java new file mode 100644 index 0000000000000..c10c3b800f83a --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizeLinkedEntitiesAsync.java @@ -0,0 +1,49 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.LinkedEntity; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously recognize the linked entities of an input text. + */ +public class RecognizeLinkedEntitiesAsync { + /** + * Main method to invoke this demo about how to recognize the linked entities of an input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The text that need be analysed. + String text = "Old Faithful is a geyser at Yellowstone Park."; + + client.recognizeLinkedEntities(text).subscribe( + result -> { + for (LinkedEntity linkedEntity : result.getLinkedEntities()) { + System.out.printf("Recognized linked entity: %s, URL: %s, data source: %s.%n", + linkedEntity.getName(), + linkedEntity.getUrl(), + linkedEntity.getDataSource()); + } + }, + error -> System.err.println("There was an error recognizing linked entity of the text." + error), + () -> System.out.println("Linked entity recognized.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePii.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePii.java index 5470ffdc6ef0f..71cc78bd856f0 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePii.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePii.java @@ -6,19 +6,19 @@ import com.azure.ai.textanalytics.models.NamedEntity; /** - * Sample demonstrate how to recognize PII(Personally Identifiable Information) entities of a text input. + * Sample demonstrates how to recognize the PII(Personally Identifiable Information) entities of an input text. */ public class RecognizePii { /** - * Main method to invoke this demo about how to analyze sentiment of a text input. + * Main method to invoke this demo about how to recognize the PII entities of an input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The text that need be analysed. @@ -26,10 +26,12 @@ public static void main(String[] args) { for (NamedEntity entity : client.recognizePiiEntities(text).getNamedEntities()) { System.out.printf( - "Recognized PII Entity: %s, Entity Type: %s, Entity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", + "Recognized personal identifiable information entity: %s, entity type: %s, entity subtype: %s, offset: %s, length: %s, score: %s.%n", entity.getText(), entity.getType(), - entity.getSubtype(), + entity.getSubtype() == null || entity.getSubtype().isEmpty() ? "N/A" : entity.getSubtype(), + entity.getOffset(), + entity.getLength(), entity.getScore()); } } diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePiiAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePiiAsync.java new file mode 100644 index 0000000000000..3186b57f3cf92 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/RecognizePiiAsync.java @@ -0,0 +1,54 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics; + +import com.azure.ai.textanalytics.models.NamedEntity; + +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously recognize the PII(Personally Identifiable Information) entities of an input + * text. + */ +public class RecognizePiiAsync { + /** + * Main method to invoke this demo about how to recognize the PII entities of an input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The text that need be analysed. + String text = "My SSN is 555-55-5555"; + + client.recognizePiiEntities(text).subscribe( + result -> { + for (NamedEntity entity : result.getNamedEntities()) { + System.out.printf( + "Recognized personal identifiable information entity: %s, entity type: %s, entity subtype: %s, offset: %s, length: %s, score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype() == null || entity.getSubtype().isEmpty() ? "N/A" : entity.getSubtype(), + entity.getOffset(), + entity.getLength(), + entity.getScore()); + } + }, + error -> System.err.println("There was an error recognizing PII entities of the text." + error), + () -> System.out.println("PII entities recognized.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocuments.java index d6cba7bfbc77f..80a1b5fbbe611 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocuments.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocuments.java @@ -17,19 +17,19 @@ import java.util.List; /** - * Sample demonstrate how to analyze sentiment of a batch of text inputs. + * Sample demonstrates how to analyze the sentiments of a batch input text. */ public class AnalyzeSentimentBatchDocuments { /** - * Main method to invoke this demo about how to analyze sentiment of a batch of text inputs. + * Main method to invoke this demo about how to analyze the sentiments of a batch input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The texts that need be analysed. @@ -38,21 +38,33 @@ public static void main(String[] args) { new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.", "en") ); + // Request options: show statistics and model version final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); - DocumentResultCollection detectedBatchResult = client.analyzeBatchSentimentWithResponse(inputs, requestOptions, Context.NONE).getValue(); - System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); - final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + // Analyzing batch sentiments + DocumentResultCollection analyzedBatchResult = client.analyzeBatchSentimentWithResponse( + inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", analyzedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = analyzedBatchResult.getStatistics(); System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getErroneousDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); - // Detecting sentiment for each of document from a batch of documents - for (AnalyzeSentimentResult analyzeSentimentResult : detectedBatchResult) { + // Analyzed sentiment for each of document from a batch of documents + for (AnalyzeSentimentResult analyzeSentimentResult : analyzedBatchResult) { + System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); + // Erroneous document + if (analyzeSentimentResult.isError()) { + System.out.printf("Cannot analyze sentiment. Error: %s%n", analyzeSentimentResult.getError().getMessage()); + continue; + } + // Valid document final TextSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); - System.out.printf("Recognized document sentiment: %s, Positive Score: %s, Neutral Score: %s, Negative Score: %s. Length of sentence: %s, Offset of sentence: %s.%n", + System.out.printf("Recognized document sentiment: %s, positive score: %s, neutral score: %s, negative score: %s, length of sentence: %s, offset of sentence: %s.%n", documentSentiment.getTextSentimentClass(), documentSentiment.getPositiveScore(), documentSentiment.getNeutralScore(), @@ -60,7 +72,7 @@ public static void main(String[] args) { documentSentiment.getLength(), documentSentiment.getOffset()); for (TextSentiment sentenceSentiment : analyzeSentimentResult.getSentenceSentiments()) { - System.out.printf("Recognized sentence sentiment: %s, Positive Score: %s, Neutral Score: %s, Negative Score: %s. Length of sentence: %s, Offset of sentence: %s.%n", + System.out.printf("Recognized sentence sentiment: %s, positive score: %s, neutral score: %s, negative score: %s, length of sentence: %s, offset of sentence: %s.%n", sentenceSentiment.getTextSentimentClass(), sentenceSentiment.getPositiveScore(), sentenceSentiment.getNeutralScore(), diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocumentsAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocumentsAsync.java new file mode 100644 index 0000000000000..cc7b8983c432c --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/AnalyzeSentimentBatchDocumentsAsync.java @@ -0,0 +1,97 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsAsyncClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.AnalyzeSentimentResult; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; +import com.azure.ai.textanalytics.models.TextSentiment; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously analyze the sentiments of a batch input text. + */ +public class AnalyzeSentimentBatchDocumentsAsync { + /** + * Main method to invoke this demo about how to analyze the sentiments of a batch input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "The hotel was dark and unclean. The restaurant had amazing gnocchi.", "en"), + new TextDocumentInput("2", "The restaurant had amazing gnocchi. The hotel was dark and unclean.", "en") + ); + + // Request options: show statistics and model version + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + + // Analyzing batch sentiments + client.analyzeBatchSentimentWithResponse(inputs, requestOptions).subscribe( + result -> { + DocumentResultCollection analyzedBatchResult = result.getValue(); + System.out.printf("Model version: %s%n", analyzedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = analyzedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Analyzed sentiment for each of document from a batch of documents + for (AnalyzeSentimentResult analyzeSentimentResult : analyzedBatchResult) { + System.out.printf("Document ID: %s%n", analyzeSentimentResult.getId()); + // Erroneous document + if (analyzeSentimentResult.isError()) { + System.out.printf("Cannot analyze sentiment. Error: %s%n", analyzeSentimentResult.getError().getMessage()); + continue; + } + // Valid document + final TextSentiment documentSentiment = analyzeSentimentResult.getDocumentSentiment(); + System.out.printf("Analyzed document sentiment: %s, positive score: %s, neutral score: %s, negative score: %s, length of sentence: %s, offset of sentence: %s.%n", + documentSentiment.getTextSentimentClass(), + documentSentiment.getPositiveScore(), + documentSentiment.getNeutralScore(), + documentSentiment.getNegativeScore(), + documentSentiment.getLength(), + documentSentiment.getOffset()); + for (TextSentiment sentenceSentiment : analyzeSentimentResult.getSentenceSentiments()) { + System.out.printf("Analyzed sentence sentiment: %s, positive score: %s, neutral score: %s, negative score: %s, length of sentence: %s, offset of sentence: %s.%n", + sentenceSentiment.getTextSentimentClass(), + sentenceSentiment.getPositiveScore(), + sentenceSentiment.getNeutralScore(), + sentenceSentiment.getNegativeScore(), + sentenceSentiment.getLength(), + sentenceSentiment.getOffset()); + } + } + }, + error -> System.err.println("There was an error analyzing sentiment of the text inputs." + error), + () -> System.out.println("Batch of sentiment analyzed.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocuments.java index fbf76134e5f7b..a33ce2f8ea6bb 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocuments.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocuments.java @@ -17,31 +17,36 @@ import java.util.List; /** - * Sample demonstrate how to detect language of a batch of text inputs. + * Sample demonstrates how to detect the languages of a batch input text. */ public class DetectLanguageBatchDocuments { /** - * Main method to invoke this demo about how to detect language of a batch of text inputs. + * Main method to invoke this demo about how to detect the languages of a batch input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The texts that need be analysed. List inputs = Arrays.asList( - new DetectLanguageInput("1", "This is written in English.", "en"), + new DetectLanguageInput("1", "This is written in English.", "us"), new DetectLanguageInput("2", "Este es un document escrito en Español.", "es") ); + // Request options: show statistics and model version final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); - final DocumentResultCollection detectedBatchResult = client.detectBatchLanguagesWithResponse(inputs, requestOptions, Context.NONE).getValue(); + + // Detecting batch languages + final DocumentResultCollection detectedBatchResult = + client.detectBatchLanguagesWithResponse(inputs, requestOptions, Context.NONE).getValue(); System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); + // Batch statistics final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); System.out.printf("Batch statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", batchStatistics.getDocumentCount(), @@ -49,16 +54,22 @@ public static void main(String[] args) { batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); - // Detecting languages for a document from a batch of documents + // Detected languages for a document from a batch of documents for (DetectLanguageResult detectLanguageResult : detectedBatchResult) { + System.out.printf("Document ID: %s%n", detectLanguageResult.getId()); + // Erroneous document + if (detectLanguageResult.isError()) { + System.out.printf("Cannot detect language. Error: %s%n", detectLanguageResult.getError().getMessage()); + continue; + } + // Valid document final DetectedLanguage detectedPrimaryLanguage = detectLanguageResult.getPrimaryLanguage(); - System.out.printf("Detected primary Language for Document: %s, %s, ISO 6391 Name: %s, Score: %s.%n", - detectLanguageResult.getId(), + System.out.printf("Detected primary language: %s, ISO 6391 name: %s, score: %s.%n", detectedPrimaryLanguage.getName(), detectedPrimaryLanguage.getIso6391Name(), detectedPrimaryLanguage.getScore()); for (DetectedLanguage detectedLanguage : detectLanguageResult.getDetectedLanguages()) { - System.out.printf("Other detected Languages: %s, ISO 6391 Name: %s, Score: %s.%n", + System.out.printf("Another detected language: %s, ISO 6391 name: %s, score: %s.%n", detectedLanguage.getName(), detectedLanguage.getIso6391Name(), detectedLanguage.getScore()); diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocumentsAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocumentsAsync.java new file mode 100644 index 0000000000000..e52f2b859489b --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/DetectLanguageBatchDocumentsAsync.java @@ -0,0 +1,91 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsAsyncClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DetectLanguageInput; +import com.azure.ai.textanalytics.models.DetectLanguageResult; +import com.azure.ai.textanalytics.models.DetectedLanguage; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously detect the languages of a batch input text. + */ +public class DetectLanguageBatchDocumentsAsync { + /** + * Main method to invoke this demo about how to detect the languages of a batch input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new DetectLanguageInput("1", "This is written in English.", "us"), + new DetectLanguageInput("2", "Este es un document escrito en Español.", "es") + ); + + // Request options: show statistics and model version + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + + // Detecting batch languages + client.detectBatchLanguagesWithResponse(inputs, requestOptions).subscribe( + result -> { + final DocumentResultCollection detectedBatchResult = result.getValue(); + System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + System.out.printf("Batch statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Detected languages for a document from a batch of documents + for (DetectLanguageResult detectLanguageResult : detectedBatchResult) { + System.out.printf("Document ID: %s%n", detectLanguageResult.getId()); + // Erroneous document + if (detectLanguageResult.isError()) { + System.out.printf("Cannot detect language. Error: %s%n", detectLanguageResult.getError().getMessage()); + continue; + } + // Valid document + final DetectedLanguage detectedPrimaryLanguage = detectLanguageResult.getPrimaryLanguage(); + System.out.printf("Detected primary language: %s, ISO 6391 name: %s, score: %s.%n", + detectedPrimaryLanguage.getName(), + detectedPrimaryLanguage.getIso6391Name(), + detectedPrimaryLanguage.getScore()); + for (DetectedLanguage detectedLanguage : detectLanguageResult.getDetectedLanguages()) { + System.out.printf("Another detected language: %s, ISO 6391 name: %s, score: %s.%n", + detectedLanguage.getName(), + detectedLanguage.getIso6391Name(), + detectedLanguage.getScore()); + } + } + }, + error -> System.err.println("There was an error detecting language of the text inputs." + error), + () -> System.out.println("Batch of language detected.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocuments.java index 4ba8ed1233daf..8af363673984e 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocuments.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocuments.java @@ -16,19 +16,19 @@ import java.util.List; /** - * Sample demonstrate how to analyze key phrases of a batch of text inputs. + * Sample demonstrates how to extract the key phrases of a batch input text. */ public class ExtractKeyPhrasesBatchDocuments { /** - * Main method to invoke this demo about how to extract key phrases of a batch of text inputs. + * Main method to invoke this demo about how to extract the key phrases of a batch input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The texts that need be analysed. @@ -37,21 +37,32 @@ public static void main(String[] args) { new TextDocumentInput("2", "The pitot tube is used to measure airspeed.", "en") ); + // Request options: show statistics and model version final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); - final DocumentResultCollection detectedBatchResult = client.extractBatchKeyPhrasesWithResponse(inputs, requestOptions, Context.NONE).getValue(); - System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); - final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + // Extracting batch key phrases + final DocumentResultCollection extractedBatchResult = client.extractBatchKeyPhrasesWithResponse(inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", extractedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = extractedBatchResult.getStatistics(); System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getErroneousDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); - // Detecting key phrase for each of document from a batch of documents - for (ExtractKeyPhraseResult extractKeyPhraseResult : detectedBatchResult) { + // Extracted key phrase for each of document from a batch of documents + for (ExtractKeyPhraseResult extractKeyPhraseResult : extractedBatchResult) { + System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId()); + // Erroneous document + if (extractKeyPhraseResult.isError()) { + System.out.printf("Cannot extract key phrases. Error: %s%n", extractKeyPhraseResult.getError().getMessage()); + continue; + } + // Valid document for (String keyPhrases : extractKeyPhraseResult.getKeyPhrases()) { - System.out.printf("Recognized Phrases: %s.%n", keyPhrases); + System.out.printf("Extracted phrases: %s.%n", keyPhrases); } } } diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocumentsAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocumentsAsync.java new file mode 100644 index 0000000000000..4991b96c8cd42 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/ExtractKeyPhrasesBatchDocumentsAsync.java @@ -0,0 +1,82 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsAsyncClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.ExtractKeyPhraseResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously extract the key phrases of a batch input text. + */ +public class ExtractKeyPhrasesBatchDocumentsAsync { + /** + * Main method to invoke this demo about how to extract the key phrases of a batch input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "My cat might need to see a veterinarian.", "en"), + new TextDocumentInput("2", "The pitot tube is used to measure airspeed.", "en") + ); + + // Request options: show statistics and model version + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + + // Extracting batch key phrases + client.extractBatchKeyPhrasesWithResponse(inputs, requestOptions).subscribe( + result -> { + final DocumentResultCollection extractedBatchResult = result.getValue(); + System.out.printf("Model version: %s%n", extractedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = extractedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Extracted key phrase for each of document from a batch of documents + for (ExtractKeyPhraseResult extractKeyPhraseResult : extractedBatchResult) { + System.out.printf("Document ID: %s%n", extractKeyPhraseResult.getId()); + // Erroneous document + if (extractKeyPhraseResult.isError()) { + System.out.printf("Cannot extract key phrases. Error: %s%n", extractKeyPhraseResult.getError().getMessage()); + continue; + } + // Valid document + for (String keyPhrases : extractKeyPhraseResult.getKeyPhrases()) { + System.out.printf("Extracted phrases: %s.%n", keyPhrases); + } + } + }, + error -> System.err.println("There was an error extracting key phrases of the text inputs." + error), + () -> System.out.println("Batch of key phrases extracted.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocuments.java index f9540371aa8b9..25c396359524f 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocuments.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocuments.java @@ -17,19 +17,19 @@ import java.util.List; /** - * Sample demonstrate how to recognize entities of a batch of text inputs. + * Sample demonstrates how to recognize the entities of a batch input text. */ public class RecognizeEntitiesBatchDocuments { /** - * Main method to invoke this demo about how to recognize entities of a batch of text inputs. + * Main method to invoke this demo about how to recognize the entities of a batch input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The texts that need be analysed. @@ -38,24 +38,36 @@ public static void main(String[] args) { new TextDocumentInput("2", "Elon Musk is the CEO of SpaceX and Tesla.", "en") ); + // Request options: show statistics and model version final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); - final DocumentResultCollection detectedBatchResult = + + // Recognizing batch entities + final DocumentResultCollection recognizedBatchResult = client.recognizeBatchEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); - System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); + System.out.printf("Model version: %s%n", recognizedBatchResult.getModelVersion()); - final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = recognizedBatchResult.getStatistics(); System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getErroneousDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); - for (RecognizeEntitiesResult recognizeEntitiesResult : detectedBatchResult) { + // Recognized entities for each of document from a batch of documents + for (RecognizeEntitiesResult recognizeEntitiesResult : recognizedBatchResult) { + System.out.printf("Document ID: %s%n", recognizeEntitiesResult.getId()); + // Erroneous document + if (recognizeEntitiesResult.isError()) { + System.out.printf("Cannot recognize entities. Error: %s%n", recognizeEntitiesResult.getError().getMessage()); + continue; + } + // Valid document for (NamedEntity entity : recognizeEntitiesResult.getNamedEntities()) { - System.out.printf("Recognized NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", + System.out.printf("Recognized entity: %s, entity type: %s, entity subtype: %s, offset: %s, length: %s, score: %s.%n", entity.getText(), entity.getType(), - entity.getSubtype(), + entity.getSubtype() == null || entity.getSubtype().isEmpty() ? "N/A" : entity.getSubtype(), entity.getOffset(), entity.getLength(), entity.getScore()); diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocumentsAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocumentsAsync.java new file mode 100644 index 0000000000000..3a39d1a213148 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeEntitiesBatchDocumentsAsync.java @@ -0,0 +1,89 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsAsyncClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.RecognizeEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously recognize the entities of a batch input text. + */ +public class RecognizeEntitiesBatchDocumentsAsync { + /** + * Main method to invoke this demo about how to recognize the entities of a batch input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "Satya Nadella is the CEO of Microsoft.", "en"), + new TextDocumentInput("2", "Elon Musk is the CEO of SpaceX and Tesla.", "en") + ); + + // Request options: show statistics and model version + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + + // Recognizing batch entities + client.recognizeBatchEntitiesWithResponse(inputs, requestOptions).subscribe( + result -> { + final DocumentResultCollection recognizedBatchResult = result.getValue(); + System.out.printf("Model version: %s%n", recognizedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = recognizedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Recognized entities for each of document from a batch of documents + for (RecognizeEntitiesResult recognizeEntitiesResult : recognizedBatchResult) { + System.out.printf("Document ID: %s%n", recognizeEntitiesResult.getId()); + // Erroneous document + if (recognizeEntitiesResult.isError()) { + System.out.printf("Cannot recognize entities. Error: %s%n", recognizeEntitiesResult.getError().getMessage()); + continue; + } + // Valid document + for (NamedEntity entity : recognizeEntitiesResult.getNamedEntities()) { + System.out.printf("Recognized entity: %s, entity type: %s, entity subtype: %s, offset: %s, length: %s, score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype() == null || entity.getSubtype().isEmpty() ? "N/A" : entity.getSubtype(), + entity.getOffset(), + entity.getLength(), + entity.getScore()); + } + } + }, + error -> System.err.println("There was an error recognizing entities of the text inputs." + error), + () -> System.out.println("Batch of entities recognized.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java index b072bc018669b..bc85a0b36a8ef 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocuments.java @@ -17,19 +17,19 @@ import java.util.List; /** - * Sample demonstrate how to recognize linked entities of a batch of text inputs. + * Sample demonstrates how to recognize the linked entities of a batch input text. */ public class RecognizeLinkedEntitiesBatchDocuments { /** - * Main method to invoke this demo about how to recognize linked entities of a batch of text inputs. + * Main method to invoke this demo about how to recognize the linked entities of a batch input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The texts that need be analysed. @@ -38,22 +38,35 @@ public static void main(String[] args) { new TextDocumentInput("2", "Mount Shasta has lenticular clouds.", "en") ); + // Request options: show statistics and model version final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); - final DocumentResultCollection detectedBatchResult = client.recognizeBatchLinkedEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); - System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); - final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + // Recognizing batch entities + final DocumentResultCollection recognizedBatchResult = client.recognizeBatchLinkedEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", recognizedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = recognizedBatchResult.getStatistics(); System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getErroneousDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); - // Detecting linked entities from a batch of documents - for (RecognizeLinkedEntitiesResult linkedEntityDocumentResult : detectedBatchResult) { + // Recognized linked entities from a batch of documents + for (RecognizeLinkedEntitiesResult linkedEntityDocumentResult : recognizedBatchResult) { + System.out.printf("Document ID: %s%n", linkedEntityDocumentResult.getId()); + // Erroneous document + if (linkedEntityDocumentResult.isError()) { + System.out.printf("Cannot recognize linked entities. Error: %s%n", linkedEntityDocumentResult.getError().getMessage()); + continue; + } + // Valid document for (LinkedEntity linkedEntity : linkedEntityDocumentResult.getLinkedEntities()) { - System.out.printf("Recognized Linked NamedEntity: %s, URL: %s, Data Source: %s%n", - linkedEntity.getName(), linkedEntity.getUrl(), linkedEntity.getDataSource()); + System.out.printf("Recognized linked entity: %s, URL: %s, data source: %s%n", + linkedEntity.getName(), + linkedEntity.getUrl(), + linkedEntity.getDataSource()); } } } diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocumentsAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocumentsAsync.java new file mode 100644 index 0000000000000..4b6038a093cf9 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizeLinkedEntitiesBatchDocumentsAsync.java @@ -0,0 +1,86 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsAsyncClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.LinkedEntity; +import com.azure.ai.textanalytics.models.RecognizeLinkedEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously recognize the linked entities of a batch input text. + */ +public class RecognizeLinkedEntitiesBatchDocumentsAsync { + /** + * Main method to invoke this demo about how to recognize the linked entities of a batch input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "Old Faithful is a geyser at Yellowstone Park.", "en"), + new TextDocumentInput("2", "Mount Shasta has lenticular clouds.", "en") + ); + + // Request options: show statistics and model version + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + + // Recognizing batch entities + client.recognizeBatchLinkedEntitiesWithResponse(inputs, requestOptions).subscribe( + result -> { + final DocumentResultCollection recognizedBatchResult = result.getValue(); + System.out.printf("Model version: %s%n", recognizedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = recognizedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Recognized linked entities from a batch of documents + for (RecognizeLinkedEntitiesResult linkedEntityDocumentResult : recognizedBatchResult) { + System.out.printf("Document ID: %s%n", linkedEntityDocumentResult.getId()); + // Erroneous document + if (linkedEntityDocumentResult.isError()) { + System.out.printf("Cannot recognize linked entities. Error: %s%n", linkedEntityDocumentResult.getError().getMessage()); + continue; + } + // Valid document + for (LinkedEntity linkedEntity : linkedEntityDocumentResult.getLinkedEntities()) { + System.out.printf("Recognized linked entities: %s, URL: %s, data source: %s%n", + linkedEntity.getName(), + linkedEntity.getUrl(), + linkedEntity.getDataSource()); + } + } + }, + error -> System.err.println("There was an error recognizing linked entities of the text inputs." + error), + () -> System.out.println("Batch of linked entities recognized.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocuments.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocuments.java index 4986f308012e6..edf4b38b63f4d 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocuments.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocuments.java @@ -6,6 +6,7 @@ import com.azure.ai.textanalytics.TextAnalyticsClient; import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.NamedEntity; import com.azure.ai.textanalytics.models.RecognizePiiEntitiesResult; import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; @@ -16,19 +17,19 @@ import java.util.List; /** - * Sample demonstrate how to recognize PII(Personally Identifiable Information) entities of a text input. + * Sample demonstrates how to recognize the PII(Personally Identifiable Information) entities of a batch input text. */ public class RecognizePiiBatchDocuments { /** - * Main method to invoke this demo about how to recognize PII entities of a batch of text inputs. + * Main method to invoke this demo about how to recognize the PII entities of a batch input text. * * @param args Unused arguments to the program. */ public static void main(String[] args) { // Instantiate a client that will be used to call the service. TextAnalyticsClient client = new TextAnalyticsClientBuilder() - .subscriptionKey("subscription-key") - .endpoint("https://servicename.cognitiveservices.azure.com/") + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") .buildClient(); // The texts that need be analysed. @@ -37,26 +38,40 @@ public static void main(String[] args) { new TextDocumentInput("2", "Visa card 4111 1111 1111 1111", "en") ); + // Request options: show statistics and model version final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); - final DocumentResultCollection detectedBatchResult = client.recognizeBatchPiiEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); - System.out.printf("Model version: %s%n", detectedBatchResult.getModelVersion()); - final TextDocumentBatchStatistics batchStatistics = detectedBatchResult.getStatistics(); + // Recognizing batch entities + final DocumentResultCollection recognizedBatchResult = + client.recognizeBatchPiiEntitiesWithResponse(inputs, requestOptions, Context.NONE).getValue(); + System.out.printf("Model version: %s%n", recognizedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = recognizedBatchResult.getStatistics(); System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", batchStatistics.getDocumentCount(), batchStatistics.getErroneousDocumentCount(), batchStatistics.getTransactionCount(), batchStatistics.getValidDocumentCount()); - // Detecting pii entities from a batch of documents - detectedBatchResult.forEach(piiEntityDocumentResult -> - piiEntityDocumentResult.getNamedEntities().forEach(entity -> - System.out.printf("Recognized Personal Identifiable Info NamedEntity: %s, NamedEntity Type: %s, NamedEntity Subtype: %s, Offset: %s, Length: %s, Score: %s.%n", + // Recognized PII entities for each of document from a batch of documents + for (RecognizePiiEntitiesResult piiEntityDocumentResult : recognizedBatchResult) { + System.out.printf("Document ID: %s%n", piiEntityDocumentResult.getId()); + // Erroneous document + if (piiEntityDocumentResult.isError()) { + System.out.printf("Cannot recognize PII entities. Error: %s%n", piiEntityDocumentResult.getError().getMessage()); + continue; + } + // Valid document + for (NamedEntity entity : piiEntityDocumentResult.getNamedEntities()) { + System.out.printf("Recognized personal identifiable information entity: %s, entity type: %s, entity subtype: %s, offset: %s, length: %s, score: %s.%n", entity.getText(), entity.getType(), - entity.getSubtype(), + entity.getSubtype() == null || entity.getSubtype().isEmpty() ? "N/A" : entity.getSubtype(), entity.getOffset(), entity.getLength(), - entity.getScore()))); + entity.getScore()); + } + } } } diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocumentsAsync.java b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocumentsAsync.java new file mode 100644 index 0000000000000..e38983e2e7d62 --- /dev/null +++ b/sdk/textanalytics/azure-ai-textanalytics/src/samples/java/com/azure/ai/textanalytics/batch/RecognizePiiBatchDocumentsAsync.java @@ -0,0 +1,90 @@ +// Copyright (c) Microsoft Corporation. All rights reserved. +// Licensed under the MIT License. + +package com.azure.ai.textanalytics.batch; + +import com.azure.ai.textanalytics.TextAnalyticsAsyncClient; +import com.azure.ai.textanalytics.TextAnalyticsClientBuilder; +import com.azure.ai.textanalytics.models.DocumentResultCollection; +import com.azure.ai.textanalytics.models.NamedEntity; +import com.azure.ai.textanalytics.models.RecognizePiiEntitiesResult; +import com.azure.ai.textanalytics.models.TextAnalyticsRequestOptions; +import com.azure.ai.textanalytics.models.TextDocumentBatchStatistics; +import com.azure.ai.textanalytics.models.TextDocumentInput; + +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.TimeUnit; + +/** + * Sample demonstrates how to asynchronously recognize the PII(Personally Identifiable Information) entities of a batch + * input text. + */ +public class RecognizePiiBatchDocumentsAsync { + /** + * Main method to invoke this demo about how to recognize the PII entities of a batch input text. + * + * @param args Unused arguments to the program. + */ + public static void main(String[] args) { + // Instantiate a client that will be used to call the service. + TextAnalyticsAsyncClient client = new TextAnalyticsClientBuilder() + .subscriptionKey("{subscription_key}") + .endpoint("https://{servicename}.cognitiveservices.azure.com/") + .buildAsyncClient(); + + // The texts that need be analysed. + List inputs = Arrays.asList( + new TextDocumentInput("1", "My SSN is 555-55-5555", "en"), + new TextDocumentInput("2", "Visa card 4111 1111 1111 1111", "en") + ); + + // Request options: show statistics and model version + final TextAnalyticsRequestOptions requestOptions = new TextAnalyticsRequestOptions().setShowStatistics(true); + + // Recognizing batch entities + client.recognizeBatchPiiEntitiesWithResponse(inputs, requestOptions).subscribe( + result -> { + final DocumentResultCollection recognizedBatchResult = result.getValue(); + System.out.printf("Model version: %s%n", recognizedBatchResult.getModelVersion()); + + // Batch statistics + final TextDocumentBatchStatistics batchStatistics = recognizedBatchResult.getStatistics(); + System.out.printf("A batch of document statistics, document count: %s, erroneous document count: %s, transaction count: %s, valid document count: %s.%n", + batchStatistics.getDocumentCount(), + batchStatistics.getErroneousDocumentCount(), + batchStatistics.getTransactionCount(), + batchStatistics.getValidDocumentCount()); + + // Recognized PII entities for each of document from a batch of documents + for (RecognizePiiEntitiesResult piiEntityDocumentResult : recognizedBatchResult) { + System.out.printf("Document ID: %s%n", piiEntityDocumentResult.getId()); + // Erroneous document + if (piiEntityDocumentResult.isError()) { + System.out.printf("Cannot recognize PII entities. Error: %s%n", piiEntityDocumentResult.getError().getMessage()); + continue; + } + // Valid document + for (NamedEntity entity : piiEntityDocumentResult.getNamedEntities()) { + System.out.printf("Recognized personal identifiable information entity: %s, entity type: %s, entity subtype: %s, offset: %s, length: %s, score: %s.%n", + entity.getText(), + entity.getType(), + entity.getSubtype() == null || entity.getSubtype().isEmpty() ? "N/A" : entity.getSubtype(), + entity.getOffset(), + entity.getLength(), + entity.getScore()); + } + } + }, + error -> System.err.println("There was an error recognizing PII entities of the text inputs." + error), + () -> System.out.println("Batch of PII entities recognized.")); + + // 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.SECONDS.sleep(5); + } catch (InterruptedException ignored) { + } + } +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientTest.java b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientTest.java index 5af526254fbeb..326293aa5fbee 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientTest.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsAsyncClientTest.java @@ -14,7 +14,6 @@ import com.azure.ai.textanalytics.models.TextSentiment; import com.azure.ai.textanalytics.models.TextSentimentClass; import com.azure.core.exception.HttpResponseException; -import com.azure.core.util.Context; import org.junit.jupiter.api.Test; import reactor.test.StepVerifier; @@ -36,7 +35,6 @@ protected void beforeTest() { } // Detected Languages - /** * Verify that we can get statistics on the collection result when given a batch input with options. */ @@ -137,7 +135,7 @@ public void detectLanguageFaultyText() { @Test public void detectLanguageDuplicateIdInput() { detectLanguageDuplicateIdRunner((inputs, options) -> { - StepVerifier.create(client.detectBatchLanguagesWithResponse(inputs, options, Context.NONE)) + StepVerifier.create(client.detectBatchLanguagesWithResponse(inputs, options)) .verifyErrorSatisfies(ex -> assertRestException(ex, HttpResponseException.class, 400)); }); } @@ -161,7 +159,7 @@ public void recognizeEntitiesForEmptyText() { .verifyComplete(); } - @Override + @Test public void recognizeEntitiesForFaultyText() { // TODO: (savaity) confirm with service team this returns no error-ed document, no exception but empty documents and error list. StepVerifier.create(client.recognizeEntities("!@#%%")) @@ -287,7 +285,7 @@ public void recognizePiiEntitiesForEmptyText() { .verifyComplete(); } - @Override + @Test public void recognizePiiEntitiesForFaultyText() { // TODO: (savaity) confirm with service team this returns no error-ed document, no exception but empty documents and error list. StepVerifier.create(client.recognizePiiEntities("!@#%%")) diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTest.java b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTest.java index ff74fe546f812..0499abf09644d 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTest.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTest.java @@ -28,7 +28,7 @@ public class TextAnalyticsClientTest extends TextAnalyticsClientTestBase { private TextAnalyticsClient client; - @Test + @Override protected void beforeTest() { client = clientSetup(httpPipeline -> new TextAnalyticsClientBuilder() .endpoint(getEndpoint()) diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTestBase.java b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTestBase.java index d8bfd0841a03d..d510d441aa9cd 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTestBase.java +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/java/com/azure/ai/textanalytics/TextAnalyticsClientTestBase.java @@ -462,6 +462,7 @@ void analyseBatchSentimentShowStatsRunner( new TextDocumentInput("1", "The restaurant had amazing gnocchi. The hotel was dark and unclean.") ); TextAnalyticsRequestOptions options = new TextAnalyticsRequestOptions().setShowStatistics(true); + showStatistics = true; testRunner.accept(textDocumentInputs, options); } @@ -695,6 +696,7 @@ private static void validateLinkedEntityMatches(List expected /** * Helper method to verify the error document. + * * @param expectedError the Error returned from the service. * @param actualError the Error returned from the API. */ @@ -890,7 +892,7 @@ static DocumentResultCollection getExpectedBatchDetectedLa DetectLanguageResult detectLanguageResult2 = new DetectLanguageResult("1", textDocumentStatistics2, null, detectedLanguage2, detectedLanguageList2); DetectLanguageResult detectLanguageResult3 = new DetectLanguageResult("2", textDocumentStatistics3, null, detectedLanguage3, detectedLanguageList3); - TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 0, 3, 3); + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(3, 3, 0, 3); List detectLanguageResultList = Arrays.asList(detectLanguageResult1, detectLanguageResult2, detectLanguageResult3); return new DocumentResultCollection<>(detectLanguageResultList, MODEL_VERSION, textDocumentBatchStatistics); @@ -910,7 +912,7 @@ static DocumentResultCollection getExpectedBatchNamedEn RecognizeEntitiesResult recognizeEntitiesResult1 = new RecognizeEntitiesResult("0", textDocumentStatistics1, null, namedEntityList1); RecognizeEntitiesResult recognizeEntitiesResult2 = new RecognizeEntitiesResult("1", textDocumentStatistics2, null, namedEntityList2); - TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 0, 2, 2); + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List recognizeEntitiesResultList = Arrays.asList(recognizeEntitiesResult1, recognizeEntitiesResult2); return new DocumentResultCollection<>(recognizeEntitiesResultList, MODEL_VERSION, textDocumentBatchStatistics); @@ -929,7 +931,7 @@ static DocumentResultCollection getExpectedBatchPiiE RecognizePiiEntitiesResult recognizeEntitiesResult1 = new RecognizePiiEntitiesResult("0", textDocumentStatistics1, null, namedEntityList1); RecognizePiiEntitiesResult recognizeEntitiesResult2 = new RecognizePiiEntitiesResult("1", textDocumentStatistics2, null, namedEntityList2); - TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 0, 2, 2); + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List recognizeEntitiesResultList = Arrays.asList(recognizeEntitiesResult1, recognizeEntitiesResult2); return new DocumentResultCollection<>(recognizeEntitiesResultList, MODEL_VERSION, textDocumentBatchStatistics); @@ -958,7 +960,7 @@ static DocumentResultCollection getExpectedBatchL RecognizeLinkedEntitiesResult recognizeLinkedEntitiesResult1 = new RecognizeLinkedEntitiesResult("0", textDocumentStatistics1, null, linkedEntityList1); RecognizeLinkedEntitiesResult recognizeLinkedEntitiesResult2 = new RecognizeLinkedEntitiesResult("1", textDocumentStatistics2, null, linkedEntityList2); - TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 0, 2, 2); + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List recognizeLinkedEntitiesResultList = Arrays.asList(recognizeLinkedEntitiesResult1, recognizeLinkedEntitiesResult2); return new DocumentResultCollection<>(recognizeLinkedEntitiesResultList, MODEL_VERSION, textDocumentBatchStatistics); @@ -974,7 +976,7 @@ static DocumentResultCollection getExpectedBatchKeyPhras ExtractKeyPhraseResult extractKeyPhraseResult1 = new ExtractKeyPhraseResult("0", textDocumentStatistics1, null, keyPhrasesList1); ExtractKeyPhraseResult extractKeyPhraseResult2 = new ExtractKeyPhraseResult("1", textDocumentStatistics2, null, keyPhrasesList2); - TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 0, 2, 2); + TextDocumentBatchStatistics textDocumentBatchStatistics = new TextDocumentBatchStatistics(2, 2, 0, 2); List extractKeyPhraseResultList = Arrays.asList(extractKeyPhraseResult1, extractKeyPhraseResult2); return new DocumentResultCollection<>(extractKeyPhraseResultList, MODEL_VERSION, textDocumentBatchStatistics); @@ -1005,6 +1007,6 @@ static DocumentResultCollection getExpectedBatchTextSent return new DocumentResultCollection<>(Arrays.asList(analyzeSentimentResult1, analyzeSentimentResult2), MODEL_VERSION, - new TextDocumentBatchStatistics(2, 0, 2, 2)); + new TextDocumentBatchStatistics(2, 2, 0, 2)); } } diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageDuplicateIdInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageDuplicateIdInput.json index d1947f240b13d..4f36ba008693f 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageDuplicateIdInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageDuplicateIdInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages?showStats=true", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "aabc5399-ae00-4ead-8ead-bca8b1989d7d", @@ -23,4 +23,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageEmptyText.json index a56c7de419118..125d1b23ee4bb 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageEmptyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageEmptyText.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "e4c37fd8-d81c-4ab7-a517-89257f475b92", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageFaultyText.json index cd8f1cf32e2ee..5e796018297d9 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageFaultyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageFaultyText.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "d3a5ab6f-88f1-4391-afe9-f45f8ab573e0", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageInvalidCountryHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageInvalidCountryHint.json index 753370943c014..a939e8fb3fe0c 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageInvalidCountryHint.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguageInvalidCountryHint.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "c628558e-16be-4406-8e3f-c16a5872ccf7", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInput.json index e3def4868e7bc..cd1caf761f369 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "3f29b175-67c1-4323-a35a-de116b207383", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatistics.json index 103dbb27b3758..fb399249cba15 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatistics.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatistics.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages?showStats=true", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages?showStats=true", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "e4223261-bd5d-4fe2-9554-e4e5446c56f4", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatisticsNew.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatisticsNew.json index a491422f609c3..78dc5f5301c36 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatisticsNew.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchInputShowStatisticsNew.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages?showStats=true", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages?showStats=true", "Headers" : { "User-Agent" : "azsdk-java-UnknownName/UnknownVersion (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "7bbf00ca-d6c7-4e17-9bf4-6bdc587fbdb1", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchListCountryHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchListCountryHint.json index 14ccbb174030d..bdc0dd1917b26 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchListCountryHint.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchListCountryHint.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "de228f54-3435-4075-bbe2-84d568ba00c5", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringInput.json index 4cdbceac895f0..3948fdfc3bdab 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "e55e2090-42ea-46ce-8916-c0302d77ef20", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringList.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringList.json index 2359237eb5f56..5af42401c1a1c 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringList.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesBatchStringList.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-UnknownName/UnknownVersion (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "f2c6afdf-c7d9-4b64-bb47-df7a395fb176", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesNullInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesNullInput.json index cb3996213cab9..d0bcd82c37930 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesNullInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectLanguagesNullInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "fffb67be-78ff-4424-baeb-3889230fdd96", @@ -23,4 +23,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectSingleTextLanguage.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectSingleTextLanguage.json index 1796873fc27a4..499490600f134 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectSingleTextLanguage.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/detectSingleTextLanguage.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/languages", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/languages", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.4; Windows 10 10.0)", "x-ms-client-request-id" : "42c2e666-5591-4307-a822-0e32dd28fde6", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInput.json index 0bf3e6ef4e5bf..25ceb4b396fa5 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/keyPhrases", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "c06ff081-7cd8-4067-9a79-4e4abeb64e19", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInputShowStatistics.json index 030a2bab35f4d..ff3104b125f81 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInputShowStatistics.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchInputShowStatistics.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases?showStats=true", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/keyPhrases?showStats=true", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "cfeb9641-e809-4708-b37f-88358eaf0312", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchStringInput.json index 610e4628ffe09..55614eba55302 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchStringInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForBatchStringInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/keyPhrases", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "df579208-6407-49fe-8fef-d54739727c5f", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForEmptyText.json index b3411766fa053..8e5ca5af1752e 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForEmptyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForEmptyText.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/keyPhrases", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "47189e17-8ea9-48d4-a991-2bdc3a4ce8a2", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForFaultyText.json index d74425aee299d..304ef66d9660d 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForFaultyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForFaultyText.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/keyPhrases", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "d825fe65-81b2-4959-8a04-323619abc8ff", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForListLanguageHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForListLanguageHint.json index 85033491096db..d750249ae6d9d 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForListLanguageHint.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForListLanguageHint.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/keyPhrases", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "d6a9fd72-8233-4c03-b4a2-c9c361a8421e", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForTextInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForTextInput.json index b6bc69f4b0f42..d28de74cbb6db 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForTextInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/extractKeyPhrasesForTextInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/keyPhrases", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/keyPhrases", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "3be7e42b-301a-4db9-970e-e707d60caeac", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInput.json index 698d0ae140d41..36af23b61fe97 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/general", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "2167dc9e-e029-4b67-85fe-a00d762e9d1c", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInputShowStatistics.json index b54014e889a22..7f1e954f5b65b 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInputShowStatistics.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchInputShowStatistics.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general?showStats=true", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/general?showStats=true", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "4c60a884-a487-4526-a413-1b76f05d11e5", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchStringInput.json index dd5dc375ffa7a..7ded1269c69bd 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchStringInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForBatchStringInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/general", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "cdf9970f-de45-405a-94e8-45b73808ae92", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForEmptyText.json index 1a8ec9d93aade..d95682eb0df56 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForEmptyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForEmptyText.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/general", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "1221c2bb-9541-4201-a2ce-ff119ba77dc9", @@ -23,4 +23,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForFaultyText.json index ba5f37f8f8555..7195afe1b6dad 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForFaultyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForFaultyText.json @@ -1,4 +1,27 @@ { - "networkCallRecords" : [ ], + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/general", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "ea8835bd-4259-4867-9c01-e1845882c1bf", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "29", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "64334c9b-a767-419f-b5d0-cfb331a405e8", + "x-aml-ta-request-id" : "84ca812c-7b19-48b3-b254-8b27ac149336", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Fri, 27 Dec 2019 22:10:43 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForListLanguageHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForListLanguageHint.json index f0eea759ad6cc..31980fd4fb92e 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForListLanguageHint.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForListLanguageHint.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/general", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "34d87319-7ac1-44f2-905a-f7b22515e361", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForTextInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForTextInput.json index f6753dd33657c..5f316cdc5699f 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForTextInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeEntitiesForTextInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/general", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/general", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "9d68d9ec-caee-470e-b90a-e9248e7e112c", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInput.json index 54444d5a507aa..8a830ad877cc7 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/linking", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "801ab3cf-aa2a-43c7-add5-e1c8e8a2b49d", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInputShowStatistics.json index 8fb51b2fe7285..f92232db6b705 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInputShowStatistics.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchInputShowStatistics.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking?showStats=true", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/linking?showStats=true", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "17da0fae-061a-4b79-a605-addb46a09b95", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchStringInput.json index 7411a24a94956..42498d9f6e13c 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchStringInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForBatchStringInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/linking", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "10dc1e7a-05e9-489f-8568-b4c8be54790d", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForEmptyText.json index 2a0c4ad6b47d8..c64b5bd922110 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForEmptyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForEmptyText.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/linking", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "9d57fa09-3847-4d14-a9aa-be82464d592b", @@ -23,4 +23,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForFaultyText.json index 723de16176b13..2ea55fb270bb3 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForFaultyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForFaultyText.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/linking", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "edab5962-f052-40b3-83f3-3a7f11e52d3e", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForListLanguageHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForListLanguageHint.json index ae7c7a9293448..f2885add08087 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForListLanguageHint.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForListLanguageHint.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/linking", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "9f604d8e-9e35-4fdd-913d-1e2b4b41ad6d", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForTextInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForTextInput.json index 84f5923c78d08..7033022a322f4 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForTextInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizeLinkedEntitiesForTextInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/linking", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/linking", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "c70b3abe-b742-4fe0-99f6-fcfb50a72ac4", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInput.json index 0566842eeab2e..04d7a5b2ac950 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/pii", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "f31748d1-e134-4658-9f48-be3468e2e46b", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInputShowStatistics.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInputShowStatistics.json index 59c29b64abd30..d8de2ec4713f8 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInputShowStatistics.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchInputShowStatistics.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii?showStats=true", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/pii?showStats=true", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "52eddf3d-3eab-4f5f-ad18-432783d88f06", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchStringInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchStringInput.json index bad174160e987..3ac82f6e88fe3 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchStringInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForBatchStringInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/pii", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "e2ca3edd-e766-4340-ad98-e8f058b51beb", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForEmptyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForEmptyText.json index 209c52bb5bb72..ce2093832905b 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForEmptyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForEmptyText.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/pii", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "08f15ac4-1e65-4f71-ab07-51ba0b33fce5", @@ -23,4 +23,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForFaultyText.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForFaultyText.json index ba5f37f8f8555..77b02c3d75303 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForFaultyText.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForFaultyText.json @@ -1,4 +1,27 @@ { - "networkCallRecords" : [ ], + "networkCallRecords" : [ { + "Method" : "POST", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/pii", + "Headers" : { + "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", + "x-ms-client-request-id" : "5e42a69b-f818-42d2-8720-25e6c136e0cc", + "Content-Type" : "application/json; charset=utf-8" + }, + "Response" : { + "Transfer-Encoding" : "chunked", + "x-envoy-upstream-service-time" : "26", + "Strict-Transport-Security" : "max-age=31536000; includeSubDomains; preload", + "x-content-type-options" : "nosniff", + "csp-billing-usage" : "CognitiveServices.TextAnalytics.BatchScoring=1", + "apim-request-id" : "29e4f8de-9b8a-496f-bbf2-c3cbea8c0fff", + "x-aml-ta-request-id" : "12f4043a-d75f-4516-bcaf-19d7b163c30d", + "retry-after" : "0", + "StatusCode" : "200", + "Body" : "{\"documents\":[{\"id\":\"0\",\"entities\":[]}],\"errors\":[],\"modelVersion\":\"2019-10-01\"}", + "Date" : "Fri, 27 Dec 2019 22:07:03 GMT", + "Content-Type" : "application/json; charset=utf-8" + }, + "Exception" : null + } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForListLanguageHint.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForListLanguageHint.json index 83913ac6f7c5e..4f22fa7aa060d 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForListLanguageHint.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForListLanguageHint.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/pii", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "f4838369-e84b-46d4-a921-71b507d889d5", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForTextInput.json b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForTextInput.json index 938a706f0dedf..4acc96906d266 100644 --- a/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForTextInput.json +++ b/sdk/textanalytics/azure-ai-textanalytics/src/test/resources/session-records/recognizePiiEntitiesForTextInput.json @@ -1,7 +1,7 @@ { "networkCallRecords" : [ { "Method" : "POST", - "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com//text/analytics/v3.0-preview.1/entities/recognition/pii", + "Uri" : "https://javatextanalyticstestresources.cognitiveservices.azure.com/text/analytics/v3.0-preview.1/entities/recognition/pii", "Headers" : { "User-Agent" : "azsdk-java-azure-ai-textanalytics/1.0.0-beta.1 (11.0.5; Windows 10 10.0)", "x-ms-client-request-id" : "8e84a84c-5f7d-4fc8-85ab-3f0078607bc9", @@ -24,4 +24,4 @@ "Exception" : null } ], "variables" : [ ] -} \ No newline at end of file +} diff --git a/sdk/textanalytics/tests.yml b/sdk/textanalytics/tests.yml index a97cc7e5909fc..ebea2a26976db 100644 --- a/sdk/textanalytics/tests.yml +++ b/sdk/textanalytics/tests.yml @@ -6,7 +6,6 @@ jobs: ServiceDirectory: textanalytics EnvVars: AZURE_TEST_MODE: RECORD - AZURE_TEXT_ANALYTICS_SUBSCRIPTION_KEY: $(java-textanalytics-test-subscription-key) AZURE_CLIENT_ID: $(aad-azure-sdk-test-client-id) AZURE_CLIENT_SECRET: $(aad-azure-sdk-test-client-secret) AZURE_TENANT_ID: $(aad-azure-sdk-test-tenant-id)